该方案的目的是fork一个新的子进程,并执行方法,该方法还具有命令行参数。如果我进入/bin/ls --help
,我得到的错误:无法使用“的execve()”成功
[email protected]:~/lab/200801076_lab3$ ./a.out
Enter the name of the executable(with full path)/bin/ls --help
Starting the executable as a new child process...
Binary file to be executed: /bin/ls
/bin/ls: unrecognized option '--help
'
Try `/bin/ls --help' for more information.
Status returned by Child process: 2
[email protected]:~/lab/200801076_lab3$
什么是正确的参数execve()
?
#include<stdio.h>
#include<string.h> //strcpy() used
#include<malloc.h> //malloc() used
#include<unistd.h> //fork() used
#include<stdlib.h> //exit() function used
#include<sys/wait.h> //waitpid() used
int main(int argc, char **argv)
{
char command[256];
char **args=NULL;
char *arg;
int count=0;
char *binary;
pid_t pid;
printf("Enter the name of the executable(with full path)");
fgets(command,256,stdin);
binary=strtok(command," ");
args=malloc(sizeof(char*)*10);
args[0]=malloc(strlen(binary)+1);
strcpy(args[0],binary);
while ((arg=strtok(NULL," "))!=NULL)
{
if (count%10 == 0) args=realloc(args,sizeof(char*)*10);
count++;
args[count]=malloc(strlen(arg));
strcpy(args[count],arg);
}
args[++count]=NULL;
if ((pid = fork()) == -1)
{
perror("Error forking...\n");
exit(1);
}
if (pid == 0)
{
printf("Starting the executable as a new child process...\n");
printf("Binary file to be executed: %s\n",binary);
execve(args[0],args,NULL);
}
else
{
int status;
waitpid(-1, &status, 0);
printf("Status returned by Child process: %d\n",WEXITSTATUS(status));
}
return 0;
}
如果程序位于同一目录中,即a.out的的目录,参数取.... guyz请帮助快..我有一个任务提交.. – 2010-02-02 17:45:55
这是不值得...要求别人完成任务,甚至不需要自己调试!叹...我已经重申了你的问题,作为'家庭作业'... grrr – t0mm13b 2010-02-02 17:55:42
我自己做了编码..我只是无法删除错误...所以,其实我试过这样做.. – 2010-02-02 18:15:10