risc-v中文社区

 找回密码
 立即注册
查看: 1510|回复: 0

linux编程(1)---创建子进程

[复制链接]

347

主题

564

帖子

2237

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
2237
发表于 2022-8-12 16:45:20 | 显示全部楼层 |阅读模式
创建子进程一,在子进程中递归打印/home目录中的内容(用exec系列函数调用第二次实验中的代码完成此功能);子进程结束的时候完成以下功能:打印字符串“Child process exited!”。打印子进程标识符,打印父进程标识符。创建子进程二, 打印子进程运行环境中环境变量“USER”的值,通过exec系列中的某个函数设置子进程”USER”环境变量值为“zhangsan”,并且让该子进程完成以下命令:“ls –li /home”.

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

void fun() {
        printf("\n");
        printf("Child process exited!!!\n");
        printf("The child's pid is: %d\n",getpid());
        printf("The father's pid is %d\n",getppid());
        printf("\n");
}

int main() {
        pid_t pid;
        pid = vfork();

        if(pid <0)
                perror("vfork");
        else if(pid == 0) {
                printf("This is the child1 !!!\n");
                atexit(fun);

                if((execl("/home/wang/test/file/test6/test","test",NULL)) < 0) {
                        perror("execl");
                        exit(0);
                }
        } else {
                printf("This is the father !!!\n");
                if(vfork() == 0) {
                        printf("This is the child2 !!!\n");
                        printf("The child2's father's pid is: %d\n",getppid());
                        char * env[] = {"USER=zhangsan",NULL};
                        char *p;

                        p = getenv("USER");
                        if(p) {
                                printf("The user is: %s\n",p);
                        }

                        system("ls -li /home");
                        if((execle("/bin/env","env",NULL,env)) < 0)
                                perror("execle");

                        exit(1);
                }
        }
        return 0;
}


————————————————
版权声明:本文为CSDN博主「ア灬格子衬衫々」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_43573663/article/details/108814671

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则



Archiver|手机版|小黑屋|risc-v中文社区

GMT+8, 2024-4-26 03:23 , Processed in 0.017770 second(s), 17 queries .

risc-v中文社区论坛 官方网站

Copyright © 2018-2021, risc-v open source

快速回复 返回顶部 返回列表