1.编程题


实现父进程打印"parent running!" 间隔1s
子进程打印"child running !" 间隔1s
父子并行执行(同时执行)

查看编程代码

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

int main(int argc, const char *argv[])
{
    pid_t pid = fork();//执行完fork函数,就会产生一个子进程,子进程从fork函数的下一行代码开始执行

    if(pid == -1)
    {
        perror("创建子进程失败");
        return -1;
    }
    else if(pid == 0)//说明当前进程是子进程,子进程会进入该条件分支
    {
        //将子进程要做的事,写入pid == 0这个分支
        while(1)
        {
            printf("child running!!\n");
            sleep(1);
        }
    }
    else if(pid > 0)//说明当前进程是父进程,父进程会进入该条件分支
    {
        //将父进程做的事,写入pid > 0这个分支
        while(1)
        {
            printf("parent running!!\n");
            sleep(1);
        }
    }

    printf("hello world!!\n");
    return 0;
}

2.程序分析

#include <stdio.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
    pid_t pid = fork();//执行完fork函数,就会产生一个子进程,子进程从fork函数的下一行代码开始执行
    int count = 0;
    if(pid == -1)
    {
        perror("创建子进程失败");
        return -1;
    }
    else if(pid == 0)//说明当前进程是子进程,子进程会进入该条件分支
    {
        count++;//在子进程中,对count +1
    }
    else if(pid > 0)//说明当前进程是父进程,父进程会进入该条件分支
    {

    }

    printf("count is %d\n",count);
    return 0;
}

查看输出结果

count is 0
linux@ubuntu:~$ count is 1

问题:为什么count值有0也有1?为什么不同?

查看答案


因为子进程栈空间中的count+1 ,值变为1
但是父进程栈空间的count 依然是保持是0 不变的
因为子进程拷贝了父进程的资源,都有自己独立的进程空间
父进程创建子进程,子进程会copy父进程资源,然后两个进程空间完全独立,子进程某个变量改变,父进程的不变
思考:如何保证子进程先运行?
在父进程中加上个延时 sleep(1);

End

本文标题:Linux C语言进程线程 练习题

本文链接:http://www.chisato.cn/index.php/archives/57/

除非另有说明,本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议

声明:转载请注明文章来源。

最后修改:2021 年 09 月 23 日 06 : 44 PM
如果觉得我的文章对你有用,请随意赞赏