虽然我认为我已经理解了C语言中fork()
, exec()
, wait()
和pid
的工作原理,但我还没有找到在程序内部运行个人程序的方法。
以下是我的代码:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h> /* for fork() */
#include<sys/types.h> /* for pid_t */
#include<sys/wait.h> /* fpr wait() */
int main(int argc, char* argv[])
{
char fileName[255];
pid_t pid;
switch (pid = fork()) {
case -1: //Did not fork properly
perror("fork");
break;
case 0: //child
execv(fileName[0],fileName);
puts("Oh my. If this prints, execv() must have failed");
exit(EXIT_FAILURE);
break;
default: //parent
//Infinite Loop
while (1) {
printf(" %s > ", argv[0]);
scanf("%s", fileName); // gets filename
if (fileName[0] == '\0') continue;
printf("\n Entered file: %s",fileName); // prints the fileName
waitpid(pid,0,0); /* wait for child to exit() */
break;
}
}
return 0;
}
我的问题如下:
I want to take a string as an input and I want to limit its scope to 255 characters. Is
char fileName[255]
and thenscanf("%s", fileName);
the way to go? Should I usegetLine()
or some other function instead?Let's say that the input is taken correctly. How do I execute say an existing hello world program. Will the input be stored in
*argv[]
? I found out that in a different program I could usestatic char *argv[] = { "echo", "Foo is my name." , NULL }; execv("/bin/echo", argv);
in order to echo "Foo is my name.". Can I do something similar with a helloWorld program?
fileName
设置为一个值”是指输入名称。按照你的写法,你使用了一个未初始化的字符字符串作为命令,这样做可能不会很好地工作。只要你以某种方式将fileName
设置为合适的值,就应该没问题。./helloWorld
和/bin/./helloWorld
都可以工作,尽管./
是不必要的(execv()
不受$PATH
影响,如果你只指定helloWorld
,它将被视为./helloWorld
)。/bin/./helloWorld
有点靠不住;/./
可以简化为/
,而且你不应该把软件放在/bin
目录下。 - Jonathan Leffler