c - printf c issues in terminal

D. Johnson

I have the following code in my main:

//testing with fork
printf("I am process: %d\n", getpid());
pid_t pid = fork();
printf("Now I am process: %d\n", getpid());
printf("fork returned %d\n", pid);
if(pid == 0){
    printf("I am child %d\n", getpid());
}

However the output on my terminal gives me this: terminal output pic

I run my program with a param of 'config_file.txt' as you can see on the first line, and the rest of it prints out fine until it hits the fork, and my cmd line comes up in between it...any ideas on why that is or how I can fix it? Is there something wrong with the code? I was just following a simple forking tutorial.

Edit: Also, after running it my program hangs there, and I have to hit enter to get my cmd line back up.

dbush

What's happening is that the parent process is finishing before the child process. When the parent finishes the prompt is displayed, however since the child is still running it continues to print output to the console.

If you want the parent to wait until the child is done, use the wait() function:

printf("I am process: %d\n", getpid());
pid_t pid = fork();
printf("Now I am process: %d\n", getpid());
printf("fork returned %d\n", pid);
if(pid == 0){
    printf("I am child %d\n", getpid());
} else {
    wait(NULL);
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related