使用fork()系统调用编写一个Unix C程序,生成阶乘,并在子进程中给出一系列序列,如1、2、6、24、120…等。 命令行中提供了序列号。 例如:
null
Input :gfg@ubuntu:~/$ gcc -o fork fork.c gfg@ubuntu:~/$ ./fork 6 Output :1 1 2 1 2 6 1 2 6 24 1 2 6 24 120 1 2 6 24 120 720 After deletion sum 1 3 9 33 153 873 Done Input :gfg@ubuntu:~/$ gcc -o fork fork.c gfg@ubuntu:~/$ ./fork -2 Output :negative number entered -2
使用fork()创建子进程。fork()返回:
- < 0 无法创建子(新)进程
- = 0 子进程
- > 0 i、 将子进程的进程ID转换为父进程。当>0时,将执行父进程。
子进程内部: 如果输入为6,则阶乘序列的前六个数字将作为子进程的输出。因为父进程和子进程都有自己的数据副本,所以子进程必须输出序列。 在父进程内部: 父进程调用wait()调用,在退出程序之前等待子进程完成。执行必要的错误检查,以确保没有在命令行上传递非负数。
// C program to illustrate factorial calculation // using fork() in C for Linux #include <stdio.h> #include <unistd.h> #include <sys/wait.h> #include <sys/types.h> #include <string.h> #include <stdlib.h> int main( int argc , char *argv[] ) { pid_t pid; if (argc != 2) { printf ( "arg missing or exceeding" ); exit (0); } // atoi converts string to integer if ( atoi ( argv[1] ) <0 ) { printf ( "negative number entered %d" , atoi (argv[1])); exit (0); } pid=fork(); if ( pid<0 ) { printf ( "failed to create child" ); exit (0); } else if ( pid==0 ) { //Child Process int ans = 0, i, j, k = 2, n; // atoi converts string to integer n = atoi (argv[1]); int arr[n],sum[n]; arr[0] = 1; // generating factorial series for (i=1 ; i<n; i++) { arr[i] = arr[i-1]*k; k++; } // printing and sum of each sub-series for (j=0; j<n; j++) { sum[j] = 0; for (i=0; i<=j; i++) { printf ( " %d " ,arr[i]); sum[j]+=arr[i]; } printf ( "" ); } for (i=0; i<n; i++) { if ((sum[i]%2) == 0) sum[i] = -1; } printf ( "After deletion sum" ); for (i=0; i<n; i++) { if (sum[i] > 0) printf ( " %d " , sum[i]); } exit (0); } // parent process else { wait(NULL); // waiting for child process to end printf ( "Done" ); } } |
编译代码 使用名称fork保存代码。C
gfg@ubuntu:~/$ gcc -o fork fork.c
输入:
gfg@ubuntu:~/$ ./fork 5
输出:
1 1 2 1 2 6 1 2 6 24 1 2 6 24 120 After deletion sum 1 3 9 33 153 Done
首先, 命令行参数 被接受。然后传递参数的数量,并检查参数是否为正。 然后,生成阶乘序列。 相关文章- C程序演示fork()和pipe()
参考资料:
- http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/fork/create.html
- http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/fork/wait.html
本文由 卡提克·阿胡亚 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END