运行结果:
- 编写程序 rxx(xx为你学号后两位), rxx -o 生成并打印一个奇数随机数,rxx -e 生成并打印一个偶数随机数。提交代码和运行结果截图。
- 编写一个多进程程序,父进程通过调用exec和rxx 打印奇数随机数,同时打印自己PID,子进程通过调用exec和rxx 打印奇数随机数,同时打印PPID和PID,提交代码和运行结果截图
- 代码1:
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <string.h>
int main(int argc,char *argv[])
{
char *o = "-o";
char *e = "-e";
int a;
srand((unsigned int)time(NULL));
if(strcmp(argv[1], o)==0)
{
printf("偶数随机数为:%d\n",rand()*2);
}
else if(strcmp(argv[1], e)==0)
{
printf("奇数随机数为:%d\n",rand()*2+1);
}
else
{
printf("none!");
}
return 0;
}
- 代码2
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<time.h>
int main()
{
pid_t pid=-1;
pid_t ppid=-1;
int status=-1;
pid=fork();
if(pid>0)
{
srand((unsigned int)time(NULL));
printf("偶数:%d\n",rand()*2);
printf("pid = %d",getpid());
printf(" ppid = %d\n",getppid());
}
else if(pid==0)
{
srand((unsigned int)time(NULL));
printf("奇数:%d\n",rand()*2+1);
printf("pid = %d\n",getpid());
}
else
{
perror("fork");
return -1;
}
return 0;
}