首页 > 解决方案 > 如何修改代码以匹配输出 Linux

问题描述

下面的代码输出孩子和父母的 PID 输出,但是需要它看起来更像下面的示例输出。我如何修改我的代码以允许这种情况发生。任何帮助是极大的赞赏。

parent process: counter=1

child process: counter=1

parent process: counter=2

child process: counter=2

代码是(编辑以修复丢失的分号并使其更具可读性):

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>

int main(void) {
    int pid;

    pid = fork();

    if (pid < 0)
    {
        printf("\n Error ");
        exit(1);
    }
    else if (pid == 0)
    {
        printf("\n Child Process ");
        printf("\n Pid is %d ", getpid());
        exit(0);
    }
    else
    {
        printf("\n Parent process ")
        printf("\n Pid is %d ", getpid());
        exit(1);
    }
}

标签: cfork

解决方案


您的代码中缺少一个;,因此它不会干净地编译。此外,没有循环输出您需要的文本。

请考虑以下内容:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int
main()
{
        pid_t pid;

        char *child  = "child";
        char *parent = "parent";
        char *me;

        pid = fork();

        if (pid < 0) {
                perror("fork()");
                exit(EXIT_FAILURE);
        } else if (pid == 0)
                me = child;
        else
                me = parent;

        for (int i = 0; i < 2; ++i)
                printf("%s: counter is %d\n", me, i + 1);

        return EXIT_SUCCESS;
}

这调用fork()并检测当前进程是子进程还是父进程。根据它是什么,我们指向me正确的字符串并进入一个短循环,它只打印我们的字符串和计数器。

输出可能是

parent: counter is 1
parent: counter is 2
child: counter is 1
child: counter is 2

推荐阅读