2016-03-02 111 views
0

我试图执行下列操作...C:父子进程

Create a new process 
obtain the PID of a process 
put a process to sleep for a defined period of time 
check process ID on the terminal 

我的程序运行,但输出是不是我希望它是和我不是很确定我要出错的地方。感谢您的时间,我真的很感激!

代码:

int main() { 
    int i; 
    pid_t pid=0; 

    /** use fork() system call to create a new process */ 
    /** if the pid returned by fork() is negative, it indicates an error */ 

    if(fork()<0) { 
     perror("fork"); 
     exit(1); 
    } 

    if(pid==0) { 
     printf("child PID= %d\n", (int) getpid()); 
     for(i=0; i<10; i++) { 
      printf("child: %d\n", i); 
      /** put process to sleep for 1 sec */ 
      sleep(1); 
     } 
    } else { 
     /* parent */ 
     /** print the parent PID */ 
     printf("parent PID= %d\n", (int) getpid()); 
     for(i=0; i<10; i++) { 
      printf("parent: %d\n", i); 
      sleep(1); 
     } 
    } 

    exit(0); 
} 

输出应该是这个样子......

parent PID=8900 
child PID=4320 
parent:0 
child:0 
child:1 
parent:1 
child:2 
parent:2 
child:3 
parent:3 
parent:4 
etc. 

,但我发现......

child PID= 97704 
child: 0 
child PID= 106388 
child: 0 
child: 1 
child: 1 
child: 2 
child: 2 
child: 3 
child: 3 
child: 4 
child: 4 
child: 5 
child: 5 
child: 6 
child: 6 
child: 7 
child: 7 
+1

'如果(fork()的< 0)' -->'如果((PID =叉())<0)' – user3386109

回答

1

如上所述,您不会将pid分配给任何东西,因此它始终为零。您还应该将您的条件更改为pid,而不是再拨打另一个fork()

int main() { 
int i; 
pid_t pid=0; 

pid = fork(); /* Add this */ 

/** use fork() system call to create a new process */ 
/** if the pid returned by fork() is negative, it indicates an error */ 

if(pid<0) { /* Change this */ 
    perror("fork"); 
    exit(1); 
} 

此外,不要惊讶,如果您的预期输出仍然看起来不同于你的期望。没有办法告诉孩子或父母什么时候会被打电话(特别是如果你睡了)。这取决于各种各样的事情。

编辑:我明白你在说什么。你想通过终端检查进程ID吗?您可以将getchar();添加到程序的最后,以暂停程序退出,然后您可以打开另一个终端并运行ps。你需要确保你添加了#include <stdio.h>,尽管如此。

+0

呀还好还好,我现在明白,我怎么会去检查进程ID?我一直告诉在执行时输入ps会显示出来,但是到目前为止ps直到程序运行完毕才会执行 – Bob

+0

我有些困惑,'ps'是一个shell命令,用于报告当前进程的信息。 id,只需检查一下pid的值,就像你在做的那样。 – MrPickles

+0

@Bob看到我上面的编辑。这是从终端获取程序进程ID的一种方法。 – MrPickles

2

你不确实将fork()的输出分配给pid,所以pid保持为零。

0

使用pid进行比较而不是调用另一个fork()。设置pid等于fork(),所以你可以比较它来检查pid中的错误。

int main() { 
    int i; 
    pid_t pid=0; 
    pid = fork(); 

    /** use fork() system call to create a new process */ 
    /** if the pid returned by fork() is negative, it indicates an error */ 

    if(pid<0) { 
     perror("fork"); 
     exit(1); 
    } 

    if(pid==0) { 
     printf("child PID= %d\n", (int) getpid()); 
     for(i=0; i<10; i++) { 
      printf("child: %d\n", i); 
      /** put process to sleep for 1 sec */ 
      sleep(1); 
     } 
    } else { 
     /* parent */ 
     /** print the parent PID */ 
     printf("parent PID= %d\n", (int) getpid()); 
     for(i=0; i<10; i++) { 
      printf("parent: %d\n", i); 
      sleep(1); 
     } 
    } 

    exit(0); 
} 
+0

请看看这个页面https:// stackoverflow.com/help并尝试重新构思您的问题,以便其他人可以更好地帮助您。 – mattmilten