C进程和fork进程

标签 c process

我正在研究操作系统,但无法真正掌握这段代码:

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>

int main() 
{
    int pid;
    int i;

    pid = fork();

    switch(pid)
    {
        case -1: 
            perror ("Error \n");
            break;

        case 0: 
            for(i=1; i < 11; i++)
                printf ("Im the son %d, My father is %d - Loop %d \n", getpid(), getppid(), i);
            break;

        default: 
            for(i=1; i < 11; i++)
                printf ("Im the father %d and my father is %d - Loop %d \n", getpid(), getppid(), i);

            wait(NULL);
            printf("End of the father process %d - My son process %d have finished.\n", getpid(), pid);
            break;
    }

}

我知道你 fork (创建进程的副本),如果一切顺利(与-1不同),那么它会在 for 中循环十次,然后中断,我不明白这就是儿子如何返回到 for 的方式,我的意思是,如果它是 0(儿子),则 printf“它是儿子 X,我的父亲是 Y”,然后中断。怎么两个都循环了10次?.

最佳答案

不带 {}

for() 仅重复执行下一行。

for(i=1; i < 11; i++)
    printf();
break;

相同
for(i=1; i < 11; i++) {
    printf();
}
break;

关于C进程和fork进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39578823/

相关文章:

c - 只在一个 child 上 fork 的 Unix fork 树

python - 当我手动终止特定的 .py 脚本时,如何仍然使用函数?

node.js - 将 Node.js 内存使用限制为每个进程小于 300MB

c# - 来自 C# : string as parameter and return value? 的 C

c - char *s[] 和 char (*s)[] 有什么区别?

C 程序显示的字符多于数组大小

c - TCP 套接字读/写卡住服务器

c - 进程地址空间中的 Linux 变量存储 - C

c++ - 如何确定处理器是 32 位还是 64 位?双核处理器是 32 位还是 64 位?

c++ - CreateRemoteThread:内存管理