• 0

[C] Using pipe


Question

I am writing a simple shell-like program. I'm stuck on writing the pipeline part. (IE: program_A | program_B )

I'm assuming I need to use pipe(), but I'm unsure how to do this exactly.

program_A reads from stdin, then it write to a pipe? The other end of this pipe is read in by program_B (but program_B normally reads from stdin, so how do I redirect it without messing up program_A?). program_B then outputs to stdout.

Do I setup the pipe, let program_A run and output to the pipe, then start program_B (after redirecting stdin to the pipe)?

Thanks!

Link to comment
https://www.neowin.net/forum/topic/845358-c-using-pipe/
Share on other sites

3 answers to this question

Recommended Posts

  • 0

Well,there are the dup functions that duplicates a file descriptor. Your program A should look something like this:

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

//all other includes

int main(void)
{
		int mypipe[2];
		char message[255];

		if(pipe(mypipe) == -1)
		{
				   perror("\nCould not pipe");
				   return 0;
		 }
		 //now the fork part,we redirect the output after we use fork
		 //since the child process is an exact copy of the parent,it will have the same pipe
		 //so we can use that communicate between the processes
		 if(fork() != 0)
		 {
					//it means that this part of if will only execute in the original process,the "parent"
					//because the fork function has different outputs in the processes
					//in the parent,it returns the child's pid which is different from 0
										//in the child it returns 0
					//1 is the default descriptor for stdout so we close this descriptor
					//so that we  can use the "free" slot to add our own output,in our case
					//the write end of the pipe,meaning mypipe[1]
					printf("\nPlease enter message");
					close(1);
					if(dup2(mypipe[1],1) == -1)
					{
							   perrror("\nCould not set stdout);
							   return 0;
					}
					//now we are ready to read from the keyboard 
					//and when it outputs something,it will output it to the write end of the pipe
					//instead of stdout
					scanf("%s",mesage);
					printf("%s",message);
					//the output will be read by the other process,or any other processes that it will start
		 }
		 else
		 {
				   close(0);
				   //we close the standard input so we can replace it with our pipe's read end
				   if(dup(mypipe[0],0) == -1)
				   {
							   perror("\nCould not duplicate descriptor");
							   return 0;
				   }
				   //now we are ready to use any of the exec commands to replace the current process with another one
				   //the new process will inherit the descriptors,so when we read anything in it
				   //it will read what the other process outputs
				   if(execlp("program_B","program_B",NULL) == -1)
				   {
							perror("\nCould not execute program");
							return 0;
				   }
		 }
		 return 0;

}

Hope that answers at least some of your questions. Be carefull though,that the program might hang if it doesn't receive any input from the other process so you need to be carefull about that. And in my case,if one of the dup's fail,the other process will still remain active.

Edited by Cold Blood
Link to comment
https://www.neowin.net/forum/topic/845358-c-using-pipe/#findComment-591844958
Share on other sites

  • 0

That was useful. So, I've gotten it so that a single pipeline will work. Now I have to get it so any number will work (prog_A | prog_B | prog_C etc).

I just need to figure out how to write the for loop. I think I should setup program_A outside, then enter a loop which pipes and starts the next programs until each is started. I'll post so code once I figure it out in case someone else in the world needs help.

Link to comment
https://www.neowin.net/forum/topic/845358-c-using-pipe/#findComment-591846678
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • How old is this tip? Seems 15-20 years old? Processor states for the CPU under Windows power options has been a thing for a long, long time. It certainly isn't new or hidden... Also, with laptops it doesn't make any difference what OS you are running, all of them are configured for battery longevity over performance, for obvious reasons.
    • I can't believe Starmer is still there...his party lost so big. He's a stubborn coot, but this is largely unenforceable, so I would imagine he'll be resigning soon. A key here is for parents to buy their kids phones sans Internet access--and set up the Internet at home, where mom and day can, you know, act like parents instead expecting the government to raise their kids.
    • EA launches in-game advertising platform for brands to "connect with audiences" by Pulasthi Ariyasinghe The gaming giant Electronic Arts is exploring more ways to inject real-life brands into its games. Announced today as EA Advertising, the new platform is attempting to make it easier for brands to reach out for deals with the company and put their products inside titles like EA Sports FC, Madden, NHL, Skate, or The Sims. EA revealed that its EA Sports side of the company brings in "hundreds of millions of players across console, PC, and mobile" every year. Fan engagement of these titles was also touted as being "extraordinary," with 23,000 NFL seasons worth of games being played in Madden NFL daily, while EA Sports FC sees over a billion matches a day. “Players come to EA’s games and live experiences every day to play, watch, create and connect,” said David Tinson, Chief Experiences Officer at Electronic Arts. “That gives brands a meaningful opportunity to show up in ways that add value and respect the player experience, while maintaining authenticity in the worlds our teams are building. With EA Advertising, we’re helping brands become part of those moments in ways that are relevant and built for players.” Using the new program EA Advertising, brands will be able to inject their products into games in real-time via dynamic placement. EA says partners will have access to everything from stadium signage in sports games and targeted adverts to in-game content custom-made for the brands. These are described as additions designed to "enhance, not disrupt" experiences. "In these interactive gameplay environments, brands become part of the game itself, reflecting how players engage with advertising in real-world contexts," adds the company "Brands can activate across live environments, tailoring placements to meet campaign objectives, and update campaigns with ongoing optimization informed by aggregated engagement insights." Current real-world brand partnerships EA has built into its games include Visa (EA Sports FC and College Football), Lowe's (EA Sports FC, Madden NFL, and College Football), Red Bull (EA SPORTS FC), Xfinity and Peacock (EA SPORTS FC), and Mountain Dew’s (College Football).
    • Will be surprised if there isn't a new ver of youtube just for labelled educational content
    • UK to ban under-16s from social media following a six-week trial with teenagers by Paul Hill Credit: Pexels A few months ago, Neowin reported that the UK was trialing a social media ban with 300 teenagers for six weeks, that testing has come to an end, and Prime Minister Keir Starmer has announced that the country will ban under-16s from social media. Starmer said that this technology is making children unhappy and making it easier for bullies to harass and abuse them. He continued to talk about the addictive nature of social media, saying that it uses an infinite scroll designed to lock users in for hours. He said this interferes with children doing their homework, reading, playing with friends outside, and going to bed on time. Tackling the idea that nothing can be done about social media, Starmer said: The government’s action won’t stop at social media either, the PM said. It plans to take action on gaming services and livestreaming platforms. Right now, he said, strangers can contact any child unchecked. He said this wouldn’t happen in real life, and the government is going to stop it from happening online, too. The Labour government has overseen the introduction of the Online Safety Act, a big change to the internet which includes age verification on adult websites. This has led to a fair bit of backlash, but overall, the government is pushing ahead with these changes.
  • Recent Achievements

    • Week One Done
      Jeroen Wilms earned a badge
      Week One Done
    • Week One Done
      rolfus earned a badge
      Week One Done
    • One Month Later
      Leroy Jethro Gibbs earned a badge
      One Month Later
    • Conversation Starter
      flexorcist earned a badge
      Conversation Starter
    • One Month Later
      AndreaB earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      511
    2. 2
      +Edouard
      200
    3. 3
      PsYcHoKiLLa
      136
    4. 4
      ATLien_0
      91
    5. 5
      Steven P.
      84
  • Tell a friend

    Love Neowin? Tell a friend!