Say i have an

int c =8;

and i want to do a fork to say do a printf

printf("hello im number blah blah");

is there a way to do that printf as many times as whatever c is equal too?
using a fork().

maybe something like

int pid;
pid=fork(c)
printf("hello im number blah blah");

Dani AI

Generated

asked whether fork() can be used to make a printf happen a specific number of times. and pointed toward looping and gave an example. The important bits to understand are what fork() actually does and how to avoid accidentally creating far more processes than intended.

If the goal is exactly C child processes (each prints once), have the original parent call fork() C times and make each child do its print and then exit immediately. Make sure children do not continue the loop (otherwise every child will fork too and the count explodes). The parent should loop and, after the forks, reap children with waitpid() so you do not leave zombies. Always check fork() for errors.

Watch out for stdio buffering. Buffers are copied across fork(), so a buffered printf can appear twice if both parent and child flush the buffer. To avoid that: flush before forking, use low-level unbuffered I/O, or have the child terminate with _exit() so it does not run stdio cleanup handlers that might double-flush. Also remember output from different processes can interleave; if ordering matters, serialize the prints or have the parent collect results.

If all you want is to print the same message C times in one process, a simple loop is the correct and lightweight solution. If you need concurrent workers, consider a worker pool (forked or threaded) instead of repeatedly forking without control.

See the POSIX details for fork() and reaping children: fork(2) man page and waitpid(2) man page.

Recommended Answers

All 4 Replies

Here's a very simple example:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char**argv)
{
	int i = 0;
	for (i = 0; i < 5; ++i)
	{
		if (fork())
		{
	
		}
		else
		{
			fputs("Hello, World!\n", stdout);
			exit(EXIT_SUCCESS);	
		}
	}
	exit(EXIT_SUCCESS);
}

Like using a for loop perhaps?

I dont think i for loop would do it.

from what i wrote above i would want to printf the quoute the number of times c is equal to, so 8 times. im not aware i can do a for loop for this???

unlesssss
i do a

int c = 8;
int i = 0;

while( i <= c)
{
printf("kdjfjfjfkf");
i++;
}

that would work wouldnt it ??

that would work wouldnt it ??

Yes that wouldn't work, wouldn't it...

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.