我有2个文件“prime.c”和“singlePrime.c”和singlePrime.c里面我想创建本身变身为“isPrime.exe”,这是做出来的“prime.c”可执行一个孩子。 我想要做的就是从isPrime.exe得到回报号码,以便取决于如果输入的号码是质不是1或0,然后保存它childNum“singlePrime.c”的main()函数的内部,从而我可以打印到终端它是否是一个素数或不基于1或0,其从“isPrime.exe”返回。 下面是我的2个文件:
prime.c:
/*
File is isPrime.c
Purpose:
a program that checks if a given number is a prime number
input:
number - a positive int entered via the command line parameters. For example isPrime 1234
output:
0 - if the input number is not a prime number
1 - if the input number is a prime number
2 - if the command line parameter is not correct
Assumption:
the program does not check if the number is a positive integer
*/
#include "stdio.h"
#include "stdlib.h"
#include <unistd.h>
#include "prime.h"
int main(int argc, char *argv[])
{
int i;
int number;
if (argc < 2) {
printf("Returning 2");
return(2);
}
else number = atoi(argv[1]);
if (isPrime(number)) {
exit(1);
}
exit(0);
}
/*
Purpose: check if the input number is a prime number
input:
number - the number to be checked
return:
0 - if the number is not a prime number
1 - if the number is a prime number
*/
int isPrime(int number)
{
int i;
for(i = 2; i*i < number; i++) {
usleep(100);
if (number % i == 0) {
printf("%d is not a prime number!",number);
return(0);
}
}
printf("%d is a prime number!",number);
return(1);
}
singlePrime.c:
#include "stdio.h"
#include "stdlib.h"
#include <unistd.h>
#include "prime.h"
int main(int argc, char *argv[])
{
int number, childNum;
if (!atoi(argv[1])) {
printf("Please use a valid integer as an argument!");
exit(1);
}
int pid = fork();
if (pid == 0) {
wait(childNum);
morph(argv[1]);
}
else {
if (childNum == 0) {
printf("The input number is not a prime number!");
exit(1);
}
else if (childNum == 1) {
printf("The input number is a prime number!");
exit(1);
}
else if (childNum == 2) {
printf("Please input a number greater than 2!");
exit(1);
}
}
}
void morph(char *number)
{
char *primeArgv[] = {
"isPrime.exe",
number,
NULL,
};
execvp("isPrime.exe",primeArgv);
}