簡體   English   中英

父/子過程打印

[英]Parent/Child process print

我正在編寫一個創建子進程的C程序。 創建子進程后,父進程應輸出兩個消息:“我是父母”,然后應顯示“父已完成”。 子過程“我是孩子”和“孩子完成”相同。 但是,我想確保,孩子的第二條消息總是在父項的第二條消息之前完成。 如何實現打印“孩子完成了”和“父母完成了”而不是打印他們的pid?

#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());
}

在父進程中調用wait(2)以使子進程完成。

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

您應該檢查wait()成功,並且main()的返回類型應該為int

您可能有一個在父級中設置的標志變量,但是子級將其清除。 然后只需檢查最后一個輸出即可。

就像是

int is_parent = 1;  // Important to create and initialize before the fork

pid = fork();

if (pid == -1) { ... }

if (pid == 0)
{
    printf("\nI am the child process, my pid = %d\n\n", getpid());
    in_parent = 0;  // We're not in the parent anymore
}
else { ... }

printf("\nThe %s is done\n\n", is_parent ? "parent" : child");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM