【问题标题】:working with process, fork command使用进程,fork 命令
【发布时间】:2016-10-29 03:39:04
【问题描述】:

我写了一个简单的代码,用fork创建新进程,然后我想看看谁是子进程,谁是父进程。 据我所知,fork 对子 pc 的返回值为 0,而对父进程的返回值为 pid 号或子进程。 不知何故,在孩子和父亲身上我都得到了 0。 有人可以向我解释这段代码有什么问题吗? 谢谢。

代码是:

#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

void main()
{
    pid_t childpid;
    int status,i;

    if(childpid = fork() == -1){
        perror("fork err");
        exit(1);
    }
    if(childpid == 0){
        printf("child process, pid number is %d and returned value from fork is %d\n",getpid(),childpid);
    }
    else{
        printf("father process, pid number is %d and returned value from fork is %d\n",getpid(),childpid);
    }



}

【问题讨论】:

  • == 的优先级高于 =

标签: c process fork


【解决方案1】:

问题来自您的第一个条件。运算符== 的优先级高于赋值运算符=。所以在你的childpid 变量中,你有fork() == -1 的布尔结果。添加括号以解决您的问题:

if((childpid = fork()) == -1){
    perror("fork err");
    exit(1);
}

为了提高可读性,请将赋值放在条件之前:

childpid = fork();
if(childpid == -1){
    perror("fork err");
    exit(1);
}

operator precedence

【讨论】:

    【解决方案2】:

    在这一行

    if(childpid = fork() == -1)
    

    您从条件 fork() == -1 而不是 pid 分配了一个值

    【讨论】:

      猜你喜欢
      • 2015-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多