It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center
7年前关闭。
好的,我要把我的代码贴出来。我解释了我以前想做的事情。把我的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;
}

这是测试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;
}

最佳答案

#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测试.c
您可能需要测试execl()是否没有失败,等等,除了一些非常小的错误之外,您基本上已经有了它。最重要的是把父printf()放在waitpid()之后。

关于c - 调用c文件时如何添加参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9123061/

10-12 18:04