Linux 下c语言(创建进程)实现Collatz猜想问题
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
int main(int argc,char *argv[])
{
pid_t pid;
int n;
//argc为传递参数的个数,argv[0]为当前执行文件名,所以argc应该>1
if(argc==1){
fprintf(stderr,"Usage:./a.out<starting value>\n");
}
//将字符型变量转换成整型变量
n=atoi(argv[1]);
//创建进程
pid=fork();
if(pid<0){
fprintf(stderr,"Fork Failed");
return -1;
}
else if (pid==0){//子进程
printf("%d ",n);
while(n!=1){
if(n%2==0){
n=n/2;
}
else{
n=n*3+1;
}
printf("%d ",n);
}
}
else{//父进程
wait(NULL);//等待子进程运行完毕
printf("Child Complete");
}
return 0;
}
资料:
1:帮助理解进程概念:
https://blog.youkuaiyun.com/u013007900/article/details/49964343
https://blog.youkuaiyun.com/Misszhoudandan/article/details/80032442
2:帮助理解main函数传递参数:https://blog.youkuaiyun.com/grey_csdn/article/details/65513394