编写一段C程序,使其完成:父进程创建一个子进程,子进程运行中显示当前系统的记录时钟;父进程运行时将数字1~100循环显示到标准输出流上;同时注意程序运行时控制其执行顺序是子进程先运行,父进程再运行。
一、创建文件并编写C程序源代码
se_22是我的Linux系统用户名
1.查看当前目录下的文件
[se_22@open ~]$ ls
aFile bFlie file_copy.c insert_data.c passwd2 testc testshell.sh
bFile file_copy insert_data motd public_html testc.c test.txt
2.创建文件process.1.c
[se_22@open ~]$ touch process1.c
3.新创建的文件已经在当前目录下了
[se_22@open ~]$ ls
aFile bFlie file_copy.c insert_data.c passwd2 public_html testc.c test.txt
bFile file_copy insert_data motd process1.c testc testshell.sh
4.编写C代码,可复制粘贴,写完后ctrl+d结束编辑
[se_22@open ~]$ cat > process1.c
#include<stdio.h>
#include<unistd.h> //包含fork、exec等许多POSIX标准定义的符号常量、类型和函数原型
#include<sys/wait.h>/*包含Linux与等待子进程相关的函数和宏,比如 wait() */
int main()
{ //本实验子进程先运行父进程再运行
int pid;
pid=fork();
if(pid<0)
{
printf("创建子进程失败\n");
}
else if(pid==0) //子进程
{
//调用 execlp("/bin/date", "date", NULL) 来执行 /bin/date 命令,输出当前日期和时间
printf("子进程运行");
execlp("/bin/date", "date", NULL);
}
else //父进程
{ wait(NULL); //等待子进程运行完成
printf("父进程运行") ;
for(int i=1;i<101;i++)
printf("%d ",i);
}
return 0;
}
二、编译 为文件加运行权限 运行 运行结果
1.编译
[se_22@open ~]$ gcc -std=c99 process1.c -o process1
2.给文件夹运行权限(可省、若报错再加上此条语句)
[se_22@open ~]$ chmod +x process1.c
3.编译后出现了新文件process1
[se_22@open ~]$ ls
aFile bFlie file_copy.c insert_data.c passwd2 process1.c testc testshell.sh
bFile file_copy insert_data motd process1 public_html testc.c test.txt
4.运行
[se_22@open ~]$ ./process1
运行结果
2024年 05月 11日 星期六 16:37:11 CST
父进程运行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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100