实验内容(1)

1.将下面代码写入experiment1.c,命令:

1
gedit experiment1.c

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>

int main() {
pid_t childpid;
int retval;
int status;

/* 创建一个新进程 */
childpid = fork();

if (childpid >= 0) { // fork() 成功
if (childpid == 0) { // 子进程
printf("CHILD: I am the child process!\n");
printf("CHILD: Here's my PID: %d\n", getpid());
printf("CHILD: My parent's PID is: %d\n", getppid());
printf("CHILD: The value of fork return is: %d\n", childpid);
printf("CHILD: Sleep for 1 second...\n");
sleep(1);
printf("CHILD: Enter an exit value (0~255): ");
scanf("%d", &retval);
printf("CHILD: Goodbye!\n");
exit(retval);
} else { // 父进程
printf("PARENT: I am the parent process!\n");
printf("PARENT: Here's my PID: %d\n", getpid());
printf("PARENT: The value of my child's PID is: %d\n", childpid);
printf("PARENT: I will now wait for my child to exit.\n");
wait(&status);
printf("PARENT: Child's exit code is: %d\n", WEXITSTATUS(status));
printf("PARENT: Goodbye!\n");
exit(0);
}
} else { // fork() 失败
perror("fork error!");
exit(1);
}
}

编译和运行程序:

1
2
gcc -o experiment1 experiment1.c
./experiment1

实验内容(2)

1.将下面代码写入experiment2.c,命令:

1
gedit experiment2.c

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>

int main() {
pid_t childpid;
int status;

/* 创建一个新进程 */
childpid = fork();

if (childpid >= 0) { // fork() 成功
if (childpid == 0) { // 子进程
printf("CHILD: I am the child process! Executing 'ls' command.\n");
execlp("ls", "ls", NULL);
perror("execlp error!"); // 如果execlp失败,将输出错误信息
exit(1);
} else { // 父进程
printf("PARENT: I am the parent process!\n");
printf("PARENT: Here's my PID: %d\n", getpid());
printf("PARENT: The value of my child's PID is: %d\n", childpid);
printf("PARENT: I will now wait for my child to exit.\n");
wait(&status);
printf("PARENT: Child terminated.\n");
printf("PARENT: Goodbye!\n");
exit(0);
}
} else { // fork() 失败
perror("fork error!");
exit(1);
}
}

编译和运行程序:

1
2
gcc -o experiment2 experiment2.c
./experiment2