Sponsored Content
Top Forums Programming C: piping and the redirect operator Post 302366066 by taiL on Wednesday 28th of October 2009 05:21:12 PM
Old 10-28-2009
C: piping and the redirect operator

Hi there,

So im having a bit of trouble here finishing up a program that involves the use of piping various unix commands in c. To be exact, I am struggling with how to make the redirect operator work.

Essentially the program it self will run a bunch of piped commands in c. For example you can give it the input:

ls -l | sort -n -r | head -n 3

and it should work as if you typed it into the terminal. My problem arises when I try to do:
ls -l | sort -n -r | head -n 3 > output.txt

My inital attempt was to search the string to see if the redirect operator existed. If so, then it would simply take some special branch where it could execute it, if not it would continue as if it did not exist. However my implementation to try this is shaky at best, so any explanation, help of what I should be doing would be greatly appreciated.

Code is attached below.

Code:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>

/*get args function*/

#define MAXARGS 256
char ** getargs(char * cmd) {
	// assumes that cmd ends with NULL
	char** argsarray;
	int nargs = 0;
	int nlen = strlen(cmd);
	int i = 0;
	argsarray = (char**) malloc(sizeof(char*) * MAXARGS);
	argsarray[0] = strtok(cmd," ");
	i = 0;
	while (argsarray[i] != NULL){
		i++;
		argsarray[i] = strtok(NULL," ");
	}
	return argsarray;
}


int main(void){

  pid_t childpid;
  int fd[256][2];
  char cmd[256];
  char * sepCmd[256];
  char * pch;

  printf("Please enter a command sequence: \n");
  gets(cmd);
  //scanf("%s", cmd);
  printf("You have entered: %s \n", cmd);
  

  printf("Attempting to split up command: \n");
  pch = strtok (cmd, "|");
  

  /* My initial idea of how to tackle redirection
  char * srch;
  srch = strchr(cmd, '>');
  int reDir;

  while(cmd != NULL) {
  if (srch != NULL){
    printf("redirect operator found\n");
    reDir = 1;
          
  }
  srch = strchr(srch+1, '>');
  }
  */
  
  
  
  int count = 0;  
    while (pch != NULL && count < 256) {
      printf("%s\n", pch);
      sepCmd[count] = pch;
      printf("The value in this array value is: %s\n", sepCmd[count]);
      pch = strtok (NULL, "|");
      count++;
  }
  
  char ** argue;
  int k;
  
  /* Block that deals with the first command given by the user */
  k = 0;
  pipe(fd[k]);
  if(!fork()) {
	  	dup2(fd[k][1], STDOUT_FILENO);
		close(fd[k][0]);
		argue = getargs(sepCmd[k]);
		execvp(argue[0], argue);
		perror(argue[0]);
		exit(0);
  }

  /*Loop that will control all other comands except the last*/
  for(k = 1; k <= count - 2; k++) {
	  close(fd[k-1][1]);
	  pipe(fd[k]);
	  
	  if(!fork()) {
		  close(fd[k][0]);
		  dup2(fd[k-1][0], STDIN_FILENO);
		  dup2(fd[k][1], STDOUT_FILENO);
		  argue = getargs(sepCmd[k]);
		  execvp(argue[0], argue);
		  perror(argue[0]);
		  exit(0);
	  }
  }
  
  
  /*Block that will take care of the last command in the sequence*/
  k = count - 1;
  
  //  if(reDir){
  //argue = getargs(sepCmd[k]);
  //open(argue[count], O_RDWR);
    
  //if(!fork()){
  //  close(fd[0]);
  //  close(fd[1]);
  //  dup2(fd[k-1][0], STDOUT_FILENO);
  //  execl("/bin/>", argue[count]);}
  //}
  //else{
     
  close(fd[k-1][1]);
  if(!fork()) {
	  dup2(fd[k-1][0], STDIN_FILENO);
	  argue = getargs(sepCmd[k]);
	  execvp(argue[0], argue);
	  perror(argue[0]);
	  exit(0);
  }
  // }
  while(waitpid(-1, NULL, 0) != -1);
}

 

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Help (Piping ls, tr, cut)

I have to: pipe ls, tr, and cut to output the size (in bytes) and name of all of the files/dirs in the current directory (including any hidden ones), with the size at the beginning of the line, followed by a single tab character, followed by the the filename. I don't know what the point of... (2 Replies)
Discussion started by: scan
2 Replies

2. Shell Programming and Scripting

piping

I am using pipes (specifically piping out) in Perl to put an array from one file into an array in a different file. I can't figure out how to transfer the array. I kow how to open the pipe : open (FILEHANDLE, "| file") or die~ but how do I transfer the array. I think it has something to do with... (1 Reply)
Discussion started by: lnatz
1 Replies

3. Programming

Help with piping program

Hi, I am trying to write a program that will pipe any number of programs together like in the linux shell. As an example, the below code tries to execute "cat data | grep int | cut -b 1-10." The problem is that the programs never get executed for some reason. It seems like the first program... (3 Replies)
Discussion started by: PuppyHusher
3 Replies

4. 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

5. Shell Programming and Scripting

Piping to ex from a script

Is anyone piping commands to ex from scripts? I.E. echo '%s/change this/to that/\nwq' | ex file.name I've been using it for years with AIX, Solaris, SGI, with variations ksh and Mandriva and others with pdksh. I've just started using CentOS with ksh and it no longer works. I've tried single... (2 Replies)
Discussion started by: mph
2 Replies

6. Programming

Piping Question

I have a piping question, I am trying to implement piping on my own shell and am having some trouble...esentially I am trying to make something to do command|command|command. I can get it to work fine if the last pipe command is not forked, but executes in the shell and then exits..but I need it... (2 Replies)
Discussion started by: mtobin1987
2 Replies

7. Shell Programming and Scripting

Piping in Perl

Hi All, I am trying to perform the below csh code in Perl, but i am unfamiliar with Perl. Can anybody give me some advice on it ? Csh Code: cat filename |grep AAA| grep BBB| awk '{print("already_appended")' (11 Replies)
Discussion started by: Raynon
11 Replies

8. UNIX for Dummies Questions & Answers

Piping GREP

Hi, I need to use a double grep so to speak. I need to grep for a particular item say BOB and then for each successful result I need to grep for another item say SMITH. I tried grep "BOB" filename | grep "SMITH" but it does not seem to work. I can achieve my desired result using an... (12 Replies)
Discussion started by: mojoman
12 Replies

9. Ubuntu

Piping with grep

Hi everybody, I have a big file with blast results (if you know what this means, otherwise look at it just as a text file with a specific form). I am trying to extract some ids from within this file, which have certain parameters. For example, some Of my IDs have the term 'No hit results'... (1 Reply)
Discussion started by: frymor
1 Replies

10. Ubuntu

Piping with grep

Hi everybody, I have a big file with blast results (if you know what this means, otherwise look at it just as a text file with a specific form). I am trying to extract some ids from within this file, which have certain parameters. For example, some Of my IDs have the term 'No hit results'... (6 Replies)
Discussion started by: frymor
6 Replies
ALTER 
OPERATOR(7) SQL Commands ALTER OPERATOR(7) NAME
ALTER OPERATOR - change the definition of an operator SYNOPSIS
ALTER OPERATOR name ( { lefttype | NONE } , { righttype | NONE } ) OWNER TO newowner DESCRIPTION
ALTER OPERATOR changes the definition of an operator. The only currently available functionality is to change the owner of the operator. You must own the operator to use ALTER OPERATOR. To alter the owner, you must also be a direct or indirect member of the new owning role, and that role must have CREATE privilege on the operator's schema. (These restrictions enforce that altering the owner doesn't do anything you couldn't do by dropping and recreating the operator. However, a superuser can alter ownership of any operator anyway.) PARAMETERS
name The name (optionally schema-qualified) of an existing operator. lefttype The data type of the operator's left operand; write NONE if the operator has no left operand. righttype The data type of the operator's right operand; write NONE if the operator has no right operand. newowner The new owner of the operator. EXAMPLES
Change the owner of a custom operator a @@ b for type text: ALTER OPERATOR @@ (text, text) OWNER TO joe; COMPATIBILITY
There is no ALTER OPERATOR statement in the SQL standard. SEE ALSO
CREATE OPERATOR [create_operator(7)], DROP OPERATOR [drop_operator(7)] SQL - Language Statements 2010-05-14 ALTER OPERATOR(7)
All times are GMT -4. The time now is 03:50 PM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy