プロセス制御Linux C fork()execl()exit()wait()

2906 ワード

プロセス制御実験:
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
#include
#include

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
", getpid());
}else {
printf("I am the parent, my pid is %d, my child pid is%d
", getpid(), pid);
}
// sleep(6);
}

#define _GNU_SOURCE
#include
#include
#include
#include

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
");
printf("pid = %d
", getpid());
int t = wait(&status);
printf("t = %d
", t);
printf("status = %d
", 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
");
int t = wait(&status);
printf("t = %d
", t);
printf("status = %d
", status);
printf("WEXITSTATUS(status)=%d
",WEXITSTATUS(status));
}
exit(5);
}