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

标签 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;
}

最佳答案

看来你想在等待子进程之后打印父进程的信息,所以在waitpid之后移动printf语句。父进程中 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. 对于pidwaitPid,最好使用pid_t 而不是int。您可以去掉 childPid
2. 您应该为 pid_t 包含 sys/types.h,为 waitpid 包含 sys/wait.h。< br/> 3. 一般在没有错误的情况下main()返回0
希望这对您有所帮助!

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

相关文章:

c - 嵌入式 C. 创建一个结构 extern 与通过引用另一个源传递它

c - 如何停止或跳转信号并转到主要?

c - 如何使用宏将宏字符串化?

python - Python 中的哈希表

linux - 在 spawing ssh 之后或之前指定 match_max 有什么区别?

c - 在没有 [] 和 () 运算符的情况下在 C 中打印出一个数组 - 怎么做?

linux - 如何在 Linux 中恢复修改过的文件

linux - 为软件包构建 rpm

c - gcc 内置的 __atomic 或 __sync 函数无法提供对全局变量的一致访问

linux - posix_fallocate 以 4K 间隔一次写入 1 个字节,导致我对 NFS 实现的熔断非常慢