程序go 2018-10-24 02:38 采纳率: 100%
浏览 302

试图存储每个子进程的 PID

I am currently learning about the fork() function in c. I was playing around with the child pid's and trying to store them within an array but keep coming across errors:

void store(int pid){
    int arr[10];
    int i = 0;
    for(i = 0; i < 10; i++){
        if(arr[i] == 0){
            arr[i] = pid;
            printArray(arr);
            break;
        }
    }
}

int stuff(int a){
    int status = fork();

    if(status == 0){
        printf("PID IS %d\n", getpid());
        store(getpid());
    }
    else {
        printf("PID IS %d\n", getpid()); 
        store(getpid());
    }

    return a + 1;
}

int main(int argc, char * argv[]){
    int a = stuff(10);

    return 0;
}

Instead, this outputs the same array with the two different PIDS in the same array index. I am not too sure what exactly is happening here and would be grateful for any explanation.

转载于:https://stackoverflow.com/questions/52960331/trying-to-store-the-pids-of-every-child-process

  • 写回答

1条回答 默认 最新

  • 10.24 2018-10-24 03:28
    关注

    Keep it in mind that fork function is called once but returns twice. The difference in the returns is that the return value in the child is 0, whereas the return value in the parent is the process ID of the new child. The child process and the parent process run in separate memory spaces.

    That's the reason why your program outputs the same array with the two different PIDS in the same array index.

    int stuff(int a){
        int status = fork();
    
        // fork will return a value of pid_t type
        pid_t status = fork();
    
        if(status == 0){
            // this is in the child process, so getpid() will return the pid of the child
            printf("PID IS %d\n", getpid());
            store(getpid());
        }
        else {
            // this is in then parent process, so getpid() will return the pid of the parent
            printf("PID IS %d\n", getpid());
            store(getpid());
        }
    
        return a + 1;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题