好吧我做錯了什麼?我在Ubuntu上這樣做,我想讓系統命令「ls」和一個參數如「-a」,然後讓孩子執行它,然後父母只是打印出來。我不明白爲什麼我一直讓「父母」返回兩次。有任何想法嗎?使用fork進行C語言編程()
#include <stdio.h>
#include <sys/types.h>
#include <time.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
#include <sys/wait.h>
void Cprocess(char *commands, char *scommands[]);
void Pprocess(void);
void main(int argc, char *argv[])
{
char *sendcommand[] = {argv[1],argv[2],0};
char *commands = argv[0];
int pid;
if((pid=fork()) ==-1)
{
perror("Error!!\n");
}
else if(pid==0)
Cprocess(commands, sendcommand);
else
{
wait(0);
printf("Parent\n");
}
}
void Cprocess(char *argv1, char *argv2[])
{
execvp(argv1, argv2);
exit(19);
}
這是不是很好的我這裏是我輸入命令:
./filename ls -a
這裏是我的結果:
filename1 filename2 filename3
Parent
Parent
你告訴你的孩子跑'command'這是'argv的[0]',它是當前程序。據推測,你的意思是複製'argv [1]'而不是'argv [0]'?或者,您可以不使用單獨的'command'命令,只需使用'sendcommand [0]'作爲'execvp()'的第一個參數。不過,我沒有跟蹤爲什麼你沒有得到運行父母的許多副本。 –
BTW:main()應該返回int。 – wildplasser