进程控制 Linux C fork() execl() exit() wait()

进程控制实验:

在linux下面使用c语言利用系统调用fork(), execl(), exit(), wait()
[b]fork()用来复制进程[/b]
int fork() turns a single process into 2 identical processes, known as the parent and the child. On success, fork() returns 0 to the child process and returns the process ID of the child process to the parent process. On failure, fork() returns -1 to the parent process, sets errno to indicate the error, and no child process is created.
[b]execl()调用外部命令[/b]
execl stands for execute and leave which means that a process will get executed and then terminated by execl.
[b]exit()[/b]
int exit(int status) - terminates the process which calls this function and returns the exit status value. Both UNIX and C (forked) programs can read the status value.
[b]wait()等待子进程执行结束[/b]
int wait (int *status_location) - will force a parent process to wait for a child process to stop or terminate. wait() return the pid of the child or -1 for an error. The exit status of the child is returned to status_location.


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

int main() {
printf("main");
pid_t pid;
pid = fork();
// son process create here, exact copy from parent process
// son process will execute the main funciton after parent process
if(pid<0) {
printf("return");
return 0;
}
if(pid==0) {
printf("I am the child, my pid is %d\n", getpid());
}else {
printf("I am the parent, my pid is %d, my child pid is%d\n", getpid(), pid);
}
// sleep(6);
}



#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

void main() {
// execl("/bin/echo", "echo", "I am in execl", (char*)0);
pid_t pid;
int status = -10;
pid=fork();
if(pid==0) {
printf("i am in son proc\n");
printf("pid = %d\n", getpid());
int t = wait(&status);
printf("t = %d\n", t);
printf("status = %d\n", status);
//子进程下面没有子进程,wait返回-1,status也未变化
sleep(3);
}else {
//wait(&status) 返回子进程的pid, status为执行exit(5)的一个值
// 当然不为5, WEXITSTATUS(status)返回值为5
// sleep(3);
// wait()会等待子进程执行结束,然后回过来的执行父进程
printf("i am in father proc\n");
int t = wait(&status);
printf("t = %d\n", t);
printf("status = %d\n", status);
printf("WEXITSTATUS(status)=%d\n",WEXITSTATUS(status));
}
exit(5);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值