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

问题描述 投票:0回答:1
下面的代码输出子代和父代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); } }

c fork
1个回答
0
投票
您的代码中缺少;,因此无法完全编译。另外,没有循环输出您需要的文本。

请考虑以下内容:

#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

© www.soinside.com 2019 - 2024. All rights reserved.