Unix Piping Problem

 
Thread Tools Search this Thread
Homework and Emergencies Homework & Coursework Questions Unix Piping Problem
# 1  
Old 09-23-2012
Unix Piping Problem

Hey guys. I'm very new to Unix. I'm pretty fluent in Java and C, but I have never actually used Unix for anything. I am in an Operating Systems course now and I have an assignment to write a piece of code that involves forks and piping. I'm stuck.

1. The problem statement, all variables and given/known data:

Write a C program that will create three processes as follows:

Code:
         A
        /   \
       /     \
      /       \
   B            C

Connect process B and C with a pipe. Process C will run ls program and send the output into the pipe. Process B will run sort program and sort the list from process C in reverse order. Process A will print "Welcome, friend!" before the list is displayed and print "Good Bye!” after the list is displayed. Do not use the sleep function. Tell me if your program works.


2. Relevant commands, code, scripts, algorithms:

n/a

3. The attempts at a solution (include all code and scripts):

Here's my crack at it...

Code:
#include <stdio.h>
#include <unistd.h>
#include <sys.wait.h>

int main() {
  int pipefd[2];
  int pid1 = 0; int pid2 = 0;
  char *lsArg[2] = {"ls", 0};
  char *rArg[2] = {"-r", 0};
  pipe(pipefd);
 
  pid1 = fork();
  if(pid == 0) {
    dup2(pipefd[1], 1);
    execv("/bin/ls", lsArg);
  }
  else {
    waitpid(pid1, NULL, 0);
  }
}


4. Complete Name of School (University), City (State), Country, Name of Professor, and Course Number (Link to Course):
Rowan University, NJ USA. Professor Xu.
h ttp ://elvis. rowan .edu/~xu/classes/os/os_f12.htm


Now I realize that I do not have the reverse thing in there, nor do I have the Welcome and goodbye message. I'm just trying to figure out where things go and how they really work.

When I run what I currently have, it lists what my "ls" would list in normal order. It also locks up and doesn't ever seem to really finish, and I can't do anything without disconnecting.

Like I said, new to Unix.. any help would be appreciated. Thanks.

Moderator's Comments:
Mod Comment edit by bakunin: please view this code tag video for how to use code tags when posting code and data.

Last edited by bakunin; 09-24-2012 at 02:42 AM..
# 2  
Old 09-24-2012
Quote:
Originally Posted by itsjimmy91
Hey guys. I'm very new to Unix. I'm pretty fluent in Java and C, but I have never actually used Unix for anything. I am in an Operating Systems course now and I have an assignment to write a piece of code that involves forks and piping. I'm stuck.

... ... ...
Code:
#include <stdio.h>
#include <unistd.h>
#include <sys.wait.h>

int main() {
  int pipefd[2];
  int pid1 = 0; int pid2 = 0;
  char *lsArg[2] = {"ls", 0};
  char *rArg[2] = {"-r", 0};
  pipe(pipefd);
 
  pid1 = fork();
  if(pid == 0) {
    dup2(pipefd[1], 1);
    execv("/bin/ls", lsArg);
  }
  else {
    waitpid(pid1, NULL, 0);
  }
}

... ... ...

Now I realize that I do not have the reverse thing in there, nor do I have the Welcome and goodbye message. I'm just trying to figure out where things go and how they really work.

When I run what I currently have, it lists what my "ls" would list in normal order. It also locks up and doesn't ever seem to really finish, and I can't do anything without disconnecting.

Like I said, new to Unix.. any help would be appreciated. Thanks.
Please use CODE tags. (I've added them in the text I quoted from your posting.)

Here are a few hints:
  1. Since you're using, but not declaring pid this code shouldn't even compile let alone hang when you run it.
  2. You need to close fd 1 in the child before calling dup2 (so that the output from ls is redirected into the write end of the pipe. Then you need to close both of the original pipe file descriptors in the child before exec'ing ls.
  3. In the parent, you need to close the write end of the pipe.
  4. If you don't want ls to hang waiting for the pipe to drain, you need to read the data in the parent that is written by the child.
  5. Don't wait in the parent for the child to exit until you've hit EOF on the data being written by the child.
  6. Check the function call return codes to verify that the functions you call return successfully. Especially when learning how to use functions that are new to you, the return codes (and the value of errno [see also perror()]) will frequently tell you what to look for when things go wrong.
# 3  
Old 09-25-2012
Hey man, thanks a lot for the replies. Sorry about the code thing. I have made a few adjustments and I think I am really close. My only problem now is that the program is not actually displaying the information in reverse. Is my reverse command not getting hit?

Code:
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

int main() {
  int pipefd[2];
  int pid1 = 0, pid2 = 0;
  char *lsArg[2] = {"ls", 0};
  char *rArg[2] = {"-r", 0};
  pipe(pipefd);

  printf("Welcome, friend!\n");
  pid1 = fork();
  if(pid1 == 0) {
    close(piped[0]);
    dup2(pipefd[1], 1);
    execv("/bin/ls", lsArg);
  }

  pid2 = fork();
  if(pid2 == 0) {
    close(piped[0]);
    dup2(pipefd[0], 0);
    execv("/bin/ls", rArg);
  }
  else {
    close(pipefd[0]);
    close(pipefd[1]);
    waitpid(pid2, NULL, 0);
  }
}

# 4  
Old 09-25-2012
You are running ls twice. I think you meant to run sort for the second exec.
# 5  
Old 09-25-2012
This line here?

Code:
execv("/bin/ls", rArg);

Maybe I'm not understand this correctly. Won't this line take what is being done in the other side of the pipe (the ls), and then do to it rArg (which is "-r")?
# 6  
Old 09-25-2012
Nope. it runs ls -r. Since ls doesn't read anything you type into it, just lists files, that's pretty pointless.

The assignment told you what command to feed ls's output into -- sort. There's an actual command named that, which does what it says on the label. Smilie

You could have just done ls -r in the very first exec to have it list in reverse order from the start, avoiding having to launch a second process. But then you wouldn't be learning how pipes work...
# 7  
Old 11-13-2012
Code:
if(pid2 == 0) {
    close(piped[0]);
    dup2(pipefd[0], 0);
    execv("/bin/ls", rArg);
  }

Is there a reason you're closing the read end and then dup'ing it? Also, in the parent of 2 you're closing the descriptor's and then waiting. Not sure if that's going to have any unintended consequences, but you may want to try closing them after the children are done.

My problem was to do a merge sort with a binary tree of forked processes so it's different as I wasn't using exec() so I'm not sure if I've been much help, but it's what I got.
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Exit code from piping in unix shell script

Hi , I have following code in my shell script : "$TS_BIN/tranfrmr" "${TS_SETTINGS}/tranfrmr_p1.stx" "${TS_LOGS}/tranfrmr_p1.err" | ( "$TS_BIN/cusparse" "${TS_SETTINGS}/cusparse_p2.stx" "${TS_LOGS}/cusparse_p2.err" | ( "$TS_BIN/tsqsort" "${TS_SETTINGS}/srtforpm_p3.stx"... (8 Replies)
Discussion started by: sonu_pal
8 Replies

2. UNIX for Dummies Questions & Answers

[SOLVED] Piping Problem

Hey, I want to create a new file (devices) with the 39th and the 40th character of the line wich is in the array line and in the file drivers. But unfortunately my try doesn't work: sed -n '$linep' drivers | cut -c 39-40 | echo >>devices Perhaps one of you can help me. Thank you! emoly ... (0 Replies)
Discussion started by: emoly
0 Replies

3. Shell Programming and Scripting

piping problem with xargs

I'm trying to pipe the output from a command into another using xargs but is not getting what I want. Running this commands: find . -name '33_cr*.rod' | xargs -n1 -t -i cut -f5 {} | sort -k1.3n | uniq | wc -l give the following output: cut -f5 ./33_cr22.rod cut -f5 ./33_cr22.rod ... 9224236... (7 Replies)
Discussion started by: ivpz
7 Replies

4. Shell Programming and Scripting

Piping Unix Variable Array values into AWK

#ksh Here is my code: ERRORLIST="43032 12001 12002 12003 12004 34019 49015 49016 49017 49018 49024 49025 49026 58004 72003 12005 12006 12007 12008 12011 12012 16024 16023" for ERROR in ${ERRORLIST} do awk -v l="$lastdate" '/^....-..-../&&$0>l{d=$0}d&&/Error: '"${ERROR}"'/{print... (3 Replies)
Discussion started by: k1ko
3 Replies

5. Shell Programming and Scripting

Problem in piping the file(s) content from zip files

Hi friends I have a zip file 1.zip which contains three text files a.txt b.txt c.txt I want to grep some text(keyword) in those 3 files without extracting all the three files to a local directoryusing the command, unzip -p 1.zip |grep "search text" >result.txt The Output file is... (2 Replies)
Discussion started by: ks_reddy
2 Replies

6. Shell Programming and Scripting

problem piping input to script with echo

I am trying to have a script run without interaction from the command line. So in my script i have a line like this echo -e "\n\n\ny\ny\n" | ./script the goal being the ability to mimic 3 Enter presses and 2 'y/n' responses with 'y' followed by enter. For some reason tho, it is not... (1 Reply)
Discussion started by: mcdef
1 Replies

7. Programming

piping from C to python in UNIX

Hi, I'm trying to wrap my head around piping in C - I've got a small C program that forks and pipes stuff from the child process to the parent process. Currently the child process calls a C program that squirts out random numbers which then pipes the result to the parent process. The... (0 Replies)
Discussion started by: Dreams in Blue
0 Replies

8. Programming

Java with Unix (Redirection + Piping)

Hi, To explain this question I will have to go into a bit of detail. I hope you don't mind. currently I have a log handler (an already compiled c++ version) and what it does is makes a log file and writes all the unix output (echo, etc) of a script to that log file. To me the log_handler is... (3 Replies)
Discussion started by: fluke_perf
3 Replies

9. Shell Programming and Scripting

problem with exit code when piping

i am writing a script to perform some mysqldumps and gzip them. The problem I am running into is that if the user specifies a database that doesn't exist, the error the mysql engine produces is still piped into gzip, and the exit code returned is 0. If I don't pipe into gzip, an exit code... (4 Replies)
Discussion started by: bitoffish
4 Replies

10. UNIX for Dummies Questions & Answers

Piping in UNIX

All, I am a UNIX novice with a question that I hope you can help me with. I have a UNIX application called "Tole" that formats and displays specific information about customers. I can display the information for up to 30 customers by seperating customer IDs using commas in this format: Tole -c... (3 Replies)
Discussion started by: simo007
3 Replies
Login or Register to Ask a Question