Hi,
I was honing my linux programming skill when this nuisance started bugging me. I wanted to create an empty file creator program. While creating a large file it must print # for progress bar. But the output shows it happening reverse way. ie. first it copies file and shows the progress bar(although the bar is filled completely thus showing that parent process is working correctly). Kindly help me in putting these progress # simultaneously to file copying. Thanks in advance.
Code:

#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>

static int status = 0;
void ding()
{
status =1;
}
int main(int argc, char* argv[])
{
int rc=0,fd,i,tem=0;
char c=' ';
int size= atoi(argv[1])*1024;
char *add=argv[2];

pid_t pid;
pid = fork();
switch(pid){
case -1:
perror("Error creating fork\n");
exit(1);

case 0:
/*child process*/
{
fd = open(add,O_WRONLY|O_CREAT,0666);
if (fd<0)
{
printf("Error creating file\n");
exit(1);
}
for(i=1;i<=size;i++)
{
tem = write(fd, &c, 1);
rc += tem;
}
printf("rc: %d\n",rc);
if(rc!=size)
perror("Error allocating size.\n");
else
kill(getppid(),SIGALRM);

close(fd);
exit(0);
}
/*child process ends*/
}
/*parent process*/
(void) signal(SIGALRM,ding);
while(1){
printf("#");
sleep(1);
if(status)
{
printf("\ndone.\n");
exit(1);
}
}
}

Output:

dheeraj@dheeraj-machine:~/linux_pro$ ./a.out 1000 temp

hangs for some time. then:

rc: 1024000
###########################
done.

Clearly these # should have been printed along with file copy process. But don't know why its not.

Number one your posting title is misleading "Problem with fork system call". The system call is working just the way its supposed to. I kind of see what your trying to do here, copy a file and display its progress at the same time...this to me sounds like a problem for threads

Number one your posting title is misleading "Problem with fork system call". The system call is working just the way its supposed to. I kind of see what your trying to do here, copy a file and display its progress at the same time...this to me sounds like a problem for threads

Thanks for reply gerard. Apologies for the title:sweat: newbie here :icon_redface:. I believe that this operation can be performed via threads. But what's the problem occuring here? As you said fork is perfect in itself so where my logic is going wrong. Kindly do guide.

Solved:cool::
replacing printf("#") in parent process with

while(1){
    printf("#");
    fflush( stdout );

So the actual problem was with buffer. Got solution from other forums. Posted here for benefits of other forum members.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.