用 C 创建第二个进程

标签 c

我是 C 编程新手,我必须这样做:

Write a program that creates a second process, and then in both processes outputs the process ID and the owners user ID.

我不知道这是否正确以及如何从这里继续。这是我所拥有的:

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

int main(void) {

    int ChildPID;

    printf("This is the parent process number %d\n",getpid());
    if ((ChildPID = fork()) == -1) {
        perror("Could not fork");
        exit(EXIT_FAILURE);
    }

    if (ChildPID == 0) {
        //----In the child process
        printf("This is the child process, number %d parent number %d\n", getpid(), getppid());
    } 

    return(EXIT_SUCCESS);
}

最佳答案

下面给出的代码给出了您的解决方案。在这里您可以清楚地识别父进程代码和子进程代码。两者都在打印其相应的 pid。

void  ExecuteChild(void);
void  ExecuteParent(void);

int  main(void)
{
    pid_t  pid;

    pid = fork();
    if (pid == 0)
        ExecuteChild();
    else
        ExecuteParent();
}

void  ExecuteChild(void)
{
    int   i;

    for (i = 1; i <= 200; i++)
        printf("CHILD[%d]: UserID[%d] printing - %d\n", getpid(),getuid(),i);
    printf(" ------------- Child Exiting -------------\n");
}

void  ExecuteParent(void)
{
    int   i;

    for (i = 1; i <= 200; i++)
        printf("PARENT[%d]: UserID[%d] printing - %d\n", getpid(),getuid(),i);
    printf(" ------------- Parent Exiting -------------\n");
}

关于用 C 创建第二个进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27417154/

相关文章:

amqp 上的 C 二进制消息

c - Unix系统编程: get a network identifier to be passed to getaddrinfo

c - 在 C 中的打印语句中添加条件字符

c - 为什么在 UNIX 中只分配最低的可用文件描述符?

c++ - 混合 C 和 C++ 时出错

c - "output popen() streams are fully bufered by default"是什么意思?

c - 链接 C 程序时使用第一个出现的实现

c - 多线程程序中的输出

c - 为什么在windows下可以,但在linux下就不行呢?

python - C 或 Python 中的双峰分布