C:父子进程

标签 c process fork parent child-process

我正在尝试执行以下操作...

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

最佳答案

您并没有真正将 fork() 的输出分配给 pid,因此 pid 保持为零。

关于C:父子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35736452/

相关文章:

c - 未使用的宏警告

c++ - 如何将光流场(float)映射到像素数据(char)以进行图像变形?

c - 如何根据有多少用户选择再次输入,在C编程中输出时打印do

c - 在 child 完成 exec 后与 child 共享文件描述符表

c++ - 寻找具有某些品质的完全内存数据库

c - Doug Lea 的 malloc 中的状态标记是如何实现的?

C - 在什么情况下调用 waitpid() 会返回 -1,表示错误?

c# - 从系统托盘恢复应用程序

linux - CentOS7 CPU利用率高

ruby - 意外的 ruby​​ 全局数组变量行为