c - 如何修改代码以匹配输出 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);
}
}
解决方案
您的代码中缺少一个;
,因此它不会干净地编译。此外,没有循环输出您需要的文本。
请考虑以下内容:
#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
推荐阅读
- python - 如何在所有列上而不是在一行上应用清洁功能?AttributeError:“系列”对象没有属性“拆分”
- node.js - 远程服务器上的 Directus
- r - 将向量的每个元素添加为 data.table 中的新列
- php - 如何适配 PHP CSV utf-8?
- python - 如何使用 ColumnTransformer 和 OrdinalEncder 进行转换?
- java - 在根项目中找不到任务“sonarqube”
- php - 有没有办法在 Symfony 上自动清除缓存?
- javascript - 计算球到达目的地所需时间的公式,球的 xy 在时间循环中更新
- caching - Apache Ignite 缓存大小限制
- angular - Angular 更新后,工厂不会从提供者返回值