• 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

    • Oddly, there was a time that UFC games were culturally relevant, largely because of the graphics and gameplay that was different than the norm. But it seems like as the sport grew in popularity, gaming outlets stopped talking about the games.
    • Microsoft Edge 149.0.4022.69 by Razvan Serea Microsoft Edge is a super fast and secure web browser from Microsoft. It works on almost any device, including PCs, iPhones and Androids. It keeps you safe online, protects your privacy, and lets you browse the web quickly. You can even use it on all your devices and keep your browsing history and favorites synced up. Built on the same technology as Chrome, Microsoft Edge has additional built-in features like Startup boost and Sleeping tabs, which boost your browsing experience with world class performance and speed that are optimized to work best with Windows. Microsoft Edge security and privacy features such as Microsoft Defender SmartScreen, Password Monitor, InPrivate search, and Kids Mode help keep you and your loved ones protected and secure online. Microsoft Edge has features to keep both you and your family protected. Enable content filters and access activity reports with your Microsoft Family Safety account and experience a kid-friendly web with Kids Mode. The new Microsoft Edge is now compatible with your favorite extensions, so it’s easy to personalize your browsing experience. Microsoft Edge 149.0.4022.69 changelog: Fixed an issue that caused the Downloads dialog to continue displaying the "Keep/Delete" prompt for .rdp files after the download completed. Stable channel security updates are listed here. Download: Microsoft Edge (64-bit) | 193.0 MB (Freeware) Download: Microsoft Edge (32-bit) | 170.0 MB Download: Microsoft Edge (ARM64) | 188.0 MB View: Microsoft Edge Website | Release History Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Save 44% on Intuit QuickBooks Desktop Pro Plus 2024 (1 User for 1-Year) by Steven Parker Today's highlighted deal comes via our Apps + Software section of the Neowin Deals store, where for only a limited time, you can save 44% on Intuit QuickBooks Desktop Pro Plus 2024 (1 User + 1 Year) for Windows. Take control of your business finances with Intuit® QuickBooks® Desktop Pro Plus 2024 Lifetime Activation for Windows. This powerful accounting software simplifies bookkeeping, expense tracking, invoicing, and financial management—all in one intuitive platform. Designed for small business owners, freelancers, and accountants, QuickBooks® Desktop Pro Plus 2024 ensures accuracy, efficiency, and seamless transaction tracking. Stay organized, save time, and manage your finances with confidence—no subscriptions, just lifetime access! Financial and business management Comprehensive Financial Management: Gain access to a full suite of features designed to handle everything from creating invoices & managing expenses to generating reports and tracking sales. Enhanced Reporting Tools: Generate professional reports & insights to make informed financial decisions and help you stay ahead of your business goals. Job Costing: Track the profitability of specific jobs or projects. Fixed Asset Management: Track the depreciation & value of fixed assets. Customer & Vendor Management: Organize information, streamline communication & enhance customer relations. Sales Order Processing: Create & manage sales orders from start to finish. Purchase Order Processing: Create & manage purchase orders to streamline vendor payments. Improved Inventory Management: Enhanced features for tracking inventory levels & costs. Automation, integration, and support Enhanced Bank Feeds: Web Connect (manual QBO imports), works on all licenses for easier bank reconciliation Time Tracking: Track employee time to accurately calculate payroll and project costs Easy Data Import: Quickly transfer financial data from Excel or older QuickBooks® versions Why choose Intuit® QuickBooks® Desktop Pro Plus 2024? Effortless Installation: Quick and easy setup with step-by-step guidance. No Hidden Costs: One-time payment—no subscriptions or recurring fees. Direct Official Download: Access the software securely from the official QuickBooks® website. Stay Up to Date: Get the latest updates and features for optimal performance. Multilingual Support: Available in multiple languages to suit your needs. Lifetime Access: A one-time purchase means no ongoing costs. IMPORTANT: Cloud integrations (QuickBooks Payments, TurboTax, and Online logins) are NOT included. Good to know: Length of access: lifetime Redemption deadline: redeem your code within 30 days of purchase Access options: Windows Max number of device(s): 2 (for 1 user only and can't be used simultaneously) Version: 2024 (United States) 64-bit Available to both NEW and EXISTING users For US customers only Updates included An Intuit QuickBooks Desktop Pro Plus 2024 (1 User + 1-Year) for Windows: Lifetime License normally costs $536, but it can be yours for just $299.99 for a limited time, a saving of $236. There are also other plans available. For specifications, and license info please click the link below. Get Intuit QuickBooks Desktop Pro Plus 2024 for just $299.99 This is a time limited deal For US customers only. Support queries If you have queries or need support for any of the Neowin Deals, please use the contact form here. Neowin Deals are managed and sold by StackCommerce who represent Neowin on an affiliate basis. Why we post these deals We post these because we earn commission on each sale so as not to rely solely on advertising, which many of our readers block. It all helps toward paying staff reporters, servers and hosting costs. So for those that keep moaning and complaining, be thankful we're still online for you to even do that. Other ways to support Neowin Whitelist Neowin by not blocking our ads Create a free member account to see fewer ads Make a donation to support our day to day running costs Subscribe to Neowin - for $14 a year, or $28 a year for an ad-free experience Disclosure: Neowin benefits from revenue of each sale made through our branded deals site powered by StackCommerce.
    • AFAIK you shouldn't be getting a consent popup at all from Canada, so I think it is to do with a VPN or private/secure DNS.
    • From what I see it's only for Insider - preview builds. Not for everybody. So...
  • Recent Achievements

    • Week One Done
      agatameier earned a badge
      Week One Done
    • One Month Later
      agatameier earned a badge
      One Month Later
    • Week One Done
      ssd21345 earned a badge
      Week One Done
    • Contributor
      MarkHughes4096 went up a rank
      Contributor
    • Dedicated
      jordanspringer earned a badge
      Dedicated
  • Popular Contributors

    1. 1
      +primortal
      507
    2. 2
      +Edouard
      175
    3. 3
      PsYcHoKiLLa
      139
    4. 4
      ATLien_0
      90
    5. 5
      Steven P.
      76
  • Tell a friend

    Love Neowin? Tell a friend!