简体   繁体   中英

C Pthreads - Parent/Child

I'm currently in the process of writing a C program that creates a child process. After creating the child process, the parent process should output two messages. The first being "I am the parent" and the second "The parent is done". The same should occur for the child process "I am the child" and "The child is done". However I want to make sure, the second message of the child is always done before the second message of the parent. How can I achieve this so the "The child is done" and "The parent is done" is printed rather than printing their pid?

This is what I currently have:

#include <unistd.h>
#include <stdio.h>

main()
{
int pid, stat_loc;


printf("\nmy pid = %d\n", getpid());
pid = fork();

if (pid == -1)
perror("error in fork");

else if (pid ==0 )
{ 
   printf("\nI am the child process, my pid = %d\n\n", getpid());


} 
else  
{
  printf("\nI am the parent process, my pid = %d\n\n", getpid());       
  sleep(2);
}  
printf("\nThe %d is done\n\n", getpid());
}

If you want to execute child first and then parents then you should use wait() in parents and exit() in child .

Use exit() to send child status to parent.

int main() {
        int pid, stat_loc;
        printf("\nmy pid = %d\n", getpid());
        pid = fork();

        if (pid == -1) {
                perror("error in fork");
                return 0;
        }
        else if (pid ==0 ) {
                printf("\nI am the child process, my pid = %d\n\n", getpid());
                sleep(5);
                exit(0);/* sending child status */
        }
        else {
                int status = 0;
                int ret = wait(&status);/* wait() returns pid of the child for which its waiting */
                printf("\nThe %d is done\n\n", ret);
                printf("\nI am the parent process, my pid = %d\n\n", getpid());  
        }
        printf("\nThe %d is done\n\n", getpid());/* getpid() returns pid of the process */
        return 0;
}

You should use wait() or one of its cousins to block the parent until the child completes. See https://linux.die.net/man/2/wait

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM