create proceess using linux

Dani AI

Generated

The thread so far is on the right track: points to the system call you need and asked for clarification. Below is a compact, practical pattern that creates exactly seven child processes without using an explicit loop to fork them: the original parent keeps forking until it has produced seven children, while each child exits immediately so it does not fork again. This avoids the exponential blowup that happens when every process keeps forking.

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

void spawn_children(int n) {
    pid_t pid;
    if (n <= 0) return;

    pid = fork();
    if (pid < 0) {
        perror("fork");
        exit(EXIT_FAILURE);
    }

    if (pid == 0) {
        /* child: do work and exit so it does not spawn further children */
        printf("child PID %d, parent PID %d\n", getpid(), getppid());
        _exit(EXIT_SUCCESS);
    } else {
        /* parent: spawn the remaining children */
        spawn_children(n - 1);
    }
}

int main(void) {
    spawn_children(7);

    /* parent waits for all children (simple loop to reap them) */
    for (int i = 0; i < 7; ++i) {
        if (wait(NULL) == -1 && errno == ECHILD) break;
    }
    puts("parent: all children reaped");
    return 0;
}

Notes and cautions:

  • Use _exit() in the child to avoid double-flushing stdio buffers if you call exit() from both parent and child.
  • Check fork errors and handle resource limits (ulimit -u) if the system refuses more processes.
  • If you see more processes than expected, children are forking again — ensure your code stops children from continuing to create processes.
  • For reference on behavior and portability, see the Linux manual pages for fork and waitpid: fork(2) — Linux manual page and waitpid(2) — Linux manual page.

Recommended Answers

All 2 Replies

processes are created by executing a program. But maybe that's not your question. You need to explain a bit more about the problem you have.

use <sys/types.h> as header file in C and use fork() call to invoke child process.....

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.