![](/img/trans.png)
[英]A menu of Linux commands (e.g ls, ipconfig etc) that forks and uses execl to run the commands as a child process
[英]Use of execv with arbitrary commands of Linux — echo, date, ls, etc
我试图了解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;
}
在分叉之前,我用这个将输入分解为令牌
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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.