我有2個文件「prime.c」和「singlePrime.c」和singlePrime.c裏面我正在嘗試創建一個可以將自身變成「isPrime.exe」的子文件,它是由「prime.c 」。我想要做的是從isPrime.exe中獲得返回數,因此根據輸入數是否爲素數,可以是1或0,然後將其存儲在「singlePrime.c」的main()函數內的childNum中,以便我可以根據從「isPrime.exe」返回的1或0打印到終端是否爲素數。下面是我的2個文件:使用wait()從子進程獲取返回碼?
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);
}
您應該使用線程,無論是POSIX線程或Windows自帶的線程API。這樣你就可以簡單地分叉線程(創建後臺子進程)並將所有內容保存在同一個可執行文件中。這比擁有多個程序簡單得多。 – dmedine 2015-04-01 17:59:41
我們被告知我們必須使用wait()函數 – user3373360 2015-04-01 18:04:54
,您可以在任何分叉線程 – dmedine 2015-04-01 21:08:28