我正在尝试理解 execv()
函数。目前这就是我所拥有的。
int mish_command_name(int argc, char *argv[])
{
pid_t id;
int status;
id = fork();
switch( id ) {
case -1: // the fork() failed
perror( "fork" );
exit( EXIT_FAILURE );
case 0: // we are the child process
// if that failed, let's try /usr/bin
execv( argv[0], argv );
perror( "execv" );
// use _exit() to avoid problems with the shared
// stdout still being used by our parent
_exit( EXIT_FAILURE );
// will never reach this statement!
break;
default: // we are the parent
break;
}
// parent will wait for child to exit
id = wait( &status );
if( id < 0 ) {
perror( "wait" );
} else {
printf( "Parent: child %d terminated, status %d\n",
id, status );
}
puts( "Parent is now exiting." );
return 0;
}
在我 fork 之前,我用这个将输入分解成 token
void forkProcess(char* buff)
{
//printf("%s\n", buff );
char *ptrArray[10];
int ptrIndex = 0;
char *cp = buff;
ptrArray[ptrIndex++] = cp;
while((cp=strchr(cp, ' ')))
{
*cp = '\0';
ptrArray[ptrIndex++] = ++cp;
}
ptrArray[ptrIndex+1] = NULL;
mish_command_name(ptrIndex, ptrArray);
}
当我输入类似“echo hello world
”的内容时,我明白了。
mish[1]> echo hello
execv: No such file or directory
Parent: child 4511 terminated, status 256
Parent is now exiting.
mish[2]> echo hello world
execv: No such file or directory
Parent: child 4512 terminated, status 256
Parent is now exiting.
对我在这里搞砸的一些见解会非常有帮助。
最佳答案
这仅仅是因为 execv
需要一个完整的路径名。尝试
/bin/echo foo
如果您想自动搜索可执行文件的 PATH,您可以使用 execvp
。
关于c - 将 execv 与 Linux 的任意命令一起使用——echo、date、ls 等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23595669/