我编写了一个使用execl的程序,我希望拥有相同的功能,但使用execv。
这是我从execl:得到的程序
#include <stdio.h>
#include <unistd.h>
int main (int argc, char *argv[])
{
int pid, status,waitPid, childPid;
pid = fork (); / Duplicate /
if (pid == 0 && pid != -1) / Branch based on return value from fork () /
{
childPid = getpid();
printf ("(The Child)nProcess ID: %d, Parent process ID: %d, Process Group ID: %dn",childPid,getppid (),getgid ());
execl("/bin/cat","cat","-b","-t","-v",argv[1],(char*)NULL);
}
else
{
printf ("(The Parent)nProcess ID: %d, The Parent Process ID: %d, Process Group ID: %dn",getpid (),getppid (),getgid ());
waitPid = wait(childPid,&status,0); / Wait for PID 0 (child) to finish . /
}
return 1;
}
然后我试着修改它,以便使用execv,但我无法让它工作(因为它会说找不到这样的文件或目录)
你用调用程序/ProgramName testfile.txt
以下是我在execv:上的尝试
#include <stdio.h>
#include <unistd.h>
int main ()
{
int pid, status,waitPid, childPid;
char *cmd_str = "cat/bin";
char *argv[] = {cmd_str, "cat","-b","-t","-v", NULL };
pid = fork (); / Duplicate /
if (pid == 0 && pid != -1) / Branch based on return value from fork () /
{
childPid = getpid();
printf ("(The Child)nProcess ID: %d, Parent process ID: %d, Process Group ID: %dn",childPid,getppid (),getgid ());
execv(cmd_str,argv);
}
else
{
printf ("(The Parent)nProcess ID: %d, The Parent Process ID: %d, Process Group ID: %dn",getpid (),getppid (),getgid ());
waitPid = wait(childPid,&status,0); / Wait for PID 0 (child) to finish . /
}
return 1;
}
任何帮助都将是巨大的,已经被困在这上面很长一段时间了。谢谢
代码中有几个错误,我记下了:
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[]) // <-- missing argc/argv
{
int pid, status,waitPid, childPid;
char *cmd_str = "/bin/cat"; // <-- copy/pasta error
char *args[] = { "cat", "-b", "-t", "-v", argv[1], NULL }; // <-- renamed to args and added argv[1]
pid = fork (); // Duplicate /
if (pid == 0) // Branch based on return value from fork () /
{
childPid = getpid();
printf ("(The Child)nProcess ID: %d, Parent process ID: %d, Process Group ID: %dn",childPid,getppid (),getgid ());
execv(cmd_str,args); // <-- renamed to args
}
else
{
printf ("(The Parent)nProcess ID: %d, The Parent Process ID: %d, Process Group ID: %dn",getpid (),getppid (),getgid ());
waitPid = wait(childPid,&status,0); // Wait for PID 0 (child) to finish . /
}
return 1;
}