我在调用c文件时如何添加参数

时间:2012-02-03 02:48:55

标签: c linux

好的,我正在发布我的代码。我之前解释过我想要做的事情。发布我的c文件,希望你能找到我的错误。谢谢 这是myfork.c

#include <stdio.h>
#include <unistd.h>
int main(int argc,char *argv[])
{
  int pid;
  int s;
  int waitPid;
  int childPid;

  pid = fork();
  if (pid == 0 && pid != -1) {
    childPid = getpid();
    printf("Child Process ID:%d, Parent ID:%d, Process "
           "Group:%d\n",childPid,getppid(),getgid());
    execl("/bin/cat","cat","-b","-t","-v",argv[1],(char*)NULL);
  } else {
    printf("Original Process ID:%d, Parent Is:%d, Process Group "
           "Is:%d\n",childPid,getppid(),getgid());
    waitPid = waitpid(childPid,&s,0);
  }
  return 1;
}

这是test.c

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main(void){
  pid_t fork_return;
  fork_return = fork();
  if (fork_return==0) {
    printf("In the CHILD process\n");
  } else {
    printf("In the PARENT process\n");
  }
  return 0;
}

2 个答案:

答案 0 :(得分:2)

您似乎想在等待孩子之后打印有关父进程的信息,因此在printf之后移动waitpid语句。父进程中childPid的值也将是垃圾。您应该使用pid代替。另外,最好分开处理-1。这些方面的东西可能是:

pid = fork();
if ( pid == -1 )
{
   perror("fork");
   /* Handle error*/
}
else if(pid == 0){
  printf("Child Process ID:%d, Parent ID:%d, Process Group:%d\n",getpid(),getppid(),getgid());
  execl("/bin/cat","cat","-b","-t","-v",argv[1],(char*)NULL);
  perror("execl"); /* Print the error message for execl failure*/
}
else{
  waitPid = waitpid(pid,&s,0); /* pid holds child's pid in parent process*/
  printf("Original Process ID:%d, Parent Is:%d, Process Group Is:%d\n",getpid(),getppid(),getgid());
}

附注:
1. pid_tint最好使用pid代替waitPidchildPid。你可以摆脱sys/types.h 2.您应该pid_t添加sys/wait.h&amp; waitpid main() 3.通常当没有错误时0会返回{{1}} 希望这有帮助!

答案 1 :(得分:1)

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(int argc, char *argv[])
{
    int pid;
    int s;
    int waitPid;
    int childPid;

    if ((pid = fork()) == -1)
    {
        perror("fork");
        exit(1);
    }

    if (pid == 0)
    {
        printf("Child Process ID:%d, Parent ID:%d, Process Group:%d\n", getpid(), getppid(), getgid());

        execl("/bin/cat", "cat", "-b", "-t", "-v", argv[1], (char*)NULL);
    }
    else
    {
        waitPid = waitpid(pid, &s, 0);

        printf("Original Process ID:%d, Parent (of parent) Is:%d, Process Group Is:%d\n", getpid(), getppid(), getgid());
    }

    return 0;
}

./ myfork test.c

你可能想测试execl()没有失败等等。除了一些非常小的错误你基本上已经有了它。最重要的是将父printf()放在waitpid()之后。