我编写了一个使用exec的程序,我想拥有相同的功能,但使用exec。
这是我的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: %d\n",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: %d\n",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: %d\n",childPid,getppid (),getgid ());
execv(cmd_str,argv);
}
else
{
printf ("(The Parent)\nProcess ID: %d, The Parent Process ID: %d, Process Group ID: %d\n",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: %d\n",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: %d\n",getpid (),getppid (),getgid ());
waitPid = wait(childPid,&status,0); // Wait for PID 0 (child) to finish . /
}
return 1;
}