简体   繁体   English

如何修改代码以匹配输出 Linux

[英]How to modify code to match output Linux

Code below outputs child and parents PID output however need it to look more like the sample output below.下面的代码输出子和父 PID 输出,但需要它看起来更像下面的示例输出。 How could I modify my code to allow this to happen.我怎么能修改我的代码以允许这种情况发生。 Any help is greatly appreciated.任何帮助是极大的赞赏。

parent process: counter=1

child process: counter=1

parent process: counter=2

child process: counter=2

The code is (edited to fix missing semicolon and make more readable):代码是(编辑以修复缺少的分号并使其更具可读性):

#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);
    }
}

You have a missing ;你有一个失踪; in your code, so it wouldn't compile cleanly.在你的代码中,所以它不会干净地编译。 Also, there is no loop outputting the text that you require.此外,没有循环输出您需要的文本。

Consider instead the following:请考虑以下情况:

#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;
}

This calls fork() and detects whether the current process is the child or the parent.这将调用fork()并检测当前进程是子进程还是父进程。 Depending on which it is, we point me to the correct string and enter a short loop that just prints our string and the counter.根据它的,我们点me到正确的字符串,然后输入一个短循环,只是打印我们的字符串和计数器。

The output may be输出可能是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM