我正在做一個項目,我必須使用fork創建一個子進程,然後父進程告訴子進程執行另一個C程序「read.c」(它從.txt文件讀取所有整數並計算平均值)通過使用execve,然後我必須通過管道將該平均值發送給父進程。我不知道如何在「process.c」程序的子進程中獲得「read.c」程序的結果的「平均值」。一些可能的朋友說,我必須將用於管道(pfd [2])的文件描述符傳遞給execve,並從其他程序(read.c)中傳遞,我必須使用管道將數據寫入到process.c程序中。但我不知道該怎麼做,所以不能正常工作。我發佈了process.c和read.c的代碼,並告訴我應該做出哪些更改以使其性能良好。如何使用execve和pipe從讀取程序到主程序的數據?
process.c
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
main()
{
int pid;
int pfd[2];
int i;
char string1[12];
snprintf(string1,12,"%i",pfd[1]);
char *args[] = {"read",&string1[0],NULL};
pipe(pfd);
pid = fork();
if(pid == 0)
{
execve("read",args,NULL);
int size = 100;
char buf[size];
close(pfd[1]);
read(pfd[0],buf,size);
printf("%s\n",buf);
}
}
read.c
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main (int argc,char *argv[],char *envp[])
{
int pfd[2];
pfd[1]= atoi(argv[1]);
close(pfd[0]);
FILE *ptr_file;
char buf[1000];
int sum = 0;
int avg =0;
int no = 0;
int count = 0;
ptr_file =fopen("data.txt","r");
if (!ptr_file)
return 1;
while (fgets(buf,1000, ptr_file)!=NULL)
{
printf(" %s \n",buf);
no = atoi(buf);
sum = sum + no;
printf("Sum = %d \n", sum);
count++;
}
fclose(ptr_file);
avg = sum/count;
printf("Average : %d \n",avg);
write(pfd[1],"hello",6);/*i just write here hello to see that it is working or not*/
return 0;
}
如果您有任何解決方案,使從read.c文件process.c的子進程輸出,那麼請告訴我。
這有什麼錯將它們作爲兩個字符串? – 2013-06-21 17:55:18
作業作業... – devnull
@ H2CO3我不知道如何傳遞整數數組作爲一個string.char * args [] = {「讀取」,(char *)pfd,NULL};我試過這個,所以它不給我任何警告,但在read.c我沒有得到我所需要的。 – TusharU