我编写了一个使用 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: %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;
}
任何帮助都会很大,现在已经坚持了很长时间。谢谢!