Search Results

Search found 24 results on 1 pages for 'dup2'.

Page 1/1 | 1 

  • after dup2, stream still contains old contents?

    - by BobTurbo
    so if I do: dup2(0, backup); // backup stdin dup2(somefile, 0); // somefile has four lines of content fgets(...stdin); // consume one line fgets(....stdin); // consume two lines dup2(backup, 0); // switch stdin back to keyboard I am finding at this point.. stdin still contains the two lines I haven't consumed. Why is that? Because there is just one buffer no matter how many times you redirect? How do I get rid of the two lines left but still remember where I was in the somefile stream when I want to go back to it?

    Read the article

  • passing pipe to threads

    - by alaamh
    I see it's easy to open pipe between two process using fork, but how we can passing open pipe to threads. Assume we need to pass out of PROGRAM A to PROGRAM B "may by more than one thread", PROGRAM B send his output to PROGRAM C #include <stdio.h> #include <stdlib.h> #include <pthread.h> struct targ_s { int fd_reader; }; void *thread1(void *arg) { struct targ_s *targ = (struct targ_s*) arg; int status, fd[2]; pid_t pid; pipe(fd); pid = fork(); if (pid == 0) { dup2(STDIN_FILENO, targ->fd_reader); close(fd[0]); dup2(fd[1], STDOUT_FILENO); close(fd[1]); execvp ("PROGRAM B", NULL); exit(1); } else { close(fd[1]); dup2(fd[0], STDIN_FILENO); close(fd[0]); execl("PROGRAM C", NULL); wait(&status); return NULL; } } int main(void) { FILE *fpipe; char *command = "PROGRAM A"; char buffer[1024]; if (!(fpipe = (FILE*) popen(command, "r"))) { perror("Problems with pipe"); exit(1); } char* outfile = "out.dat"; FILE* f = fopen (outfile, "wb"); int fd = fileno( f ); struct targ_s targ; targ.fd_reader = fd; pthread_t thid; if (pthread_create(&thid, NULL, thread1, &targ) != 0) { perror("pthread_create() error"); exit(1); } int len; while (read(fpipe, buffer, sizeof (buffer)) != 0) { len = strlen(buffer); write(fd, buffer, len); } pclose(fpipe); return (0); }

    Read the article

  • Thread feeding other MultiThreading

    - by alaamh
    I see it's easy to open pipe between two process using fork, but how we can passing open pipe to threads. Assume we need to pass out of PROGRAM A to PROGRAM B "may by more than one thread", PROGRAM B send his output to PROGRAM C #include <stdio.h> #include <stdlib.h> #include <pthread.h> struct targ_s { char* reader; }; void *thread1(void *arg) { struct targ_s *targ = (struct targ_s*) arg; int status, fd[2]; pid_t pid; pipe(fd); pid = fork(); if (pid == 0) { int fd = fileno( targ->fd_reader ); dup2(STDIN_FILENO, fd); close(fd[0]); dup2(fd[1], STDOUT_FILENO); close(fd[1]); execvp ("PROGRAM B", NULL); exit(1); } else { close(fd[1]); dup2(fd[0], STDIN_FILENO); close(fd[0]); execl("PROGRAM C", NULL); wait(&status); return NULL; } } int main(void) { FILE *fpipe; char *command = "PROGRAM A"; char buffer[1024]; if (!(fpipe = (FILE*) popen(command, "r"))) { perror("Problems with pipe"); exit(1); } char* outfile = "out.dat"; FILE* f = fopen (outfile, "wb"); int fd = fileno( f ); struct targ_s targ; targ.fd_reader = outfile; pthread_t thid; if (pthread_create(&thid, NULL, thread1, &targ) != 0) { perror("pthread_create() error"); exit(1); } int len; while (read(fpipe, buffer, sizeof (buffer)) != 0) { len = strlen(buffer); write(fd, buffer, len); } pclose(fpipe); return (0); }

    Read the article

  • open file for reading multibale time for reading

    - by alaamh
    I want to use dup2 to read from input file and redirect it to the input of exec function. but my problem is i have three running process all of them have to open same input file but they do different jobs. what your suggest in such case? i don't know if it is possible to use "cat data.txt" to feed the input for the three other process but i don't know the way to do that.

    Read the article

  • Forking with Pipes

    - by Luke
    Hello I have tried to do fork() and piping in main and it works perfectly fine but when I try to implement it in a function for some reason I don't get any output, this is my code: void cmd(int **pipefd,int count,int type, int last); int main(int argc, char *argv[]) { int pipefd[3][2]; int i, total_cmds = 3,count = 0; int in = 1; for(i = 0; i < total_cmds;i++){ pipe(pipefd[count++]); cmd(pipefd,count,i,0); } /*Last Command*/ cmd(pipefd,count,i,1); exit(EXIT_SUCCESS); } void cmd(int **pipefd,int count,int type, int last){ int child_pid,i,i2; if ((child_pid = fork()) == 0) { if(count == 1){ dup2(pipefd[count-1][1],1); /*first command*/ } else if(last!=0){ dup2(pipefd[count - 2][0],0); /*middle commands*/ dup2(pipefd[count - 1][1],1); } else if(last == 1){ dup2(pipefd[count - 1][0],0); /*last command*/ } for(i = 0; i < count;i++){/*close pipes*/ for(i2 = 0; i2 < 2;i2++){ close(pipefd[i][i2]); }} if(type == 0){ execlp("ls","ls","-al",NULL); } else if(type == 1){ execlp("grep","grep",".bak",NULL); } else if(type==2){ execl("/usr/bin/wc","wc",NULL); } else if(type ==3){ execl("/usr/bin/wc","wc","-l",NULL); } perror("exec"); exit(EXIT_FAILURE); } else if (child_pid < 0) { perror("fork"); exit(EXIT_FAILURE); } } I checked the file descriptors and it is opening the right ones, not sure what the problem could be..

    Read the article

  • Can't seem to get C TCP Server-Client Communications Right

    - by Zeesponge
    Ok i need some serious help here. I have to make a TCP Server Client. When the Client connects to server using a three stage handshake. AFterwards... while the Client is running in the terminal, the user enters linux shell commands like xinput list, ls -1, ect... something that uses standard output. The server accepts the commands and uses system() (in a fork() in an infinite loop) to run the commands and the standard output is redirected to the client, where the client prints out each line. Afterward the server sends a completion signal of "\377\n". In which the client goes back to the command prompt asking for a new command and closes its connection and exit()'s when inputting "quit". I know that you have to dup2() both the STDOUT_FILENO and STDERR_FILENO to the clients file descriptor {dup2(client_FD, STDOUT_FILENO). Everything works accept when it comes for the client to retrieve system()'s stdout and printing it out... all i get is a blank line with a blinking cursor (client waiting on stdin). I tried all kinds of different routes with no avail... If anyone can help out i would greatly appreciate it TCP SERVER CODE include #include <sys/socket.h> #include <stdio.h> #include <string.h> #include <netinet/in.h> #include <signal.h> #include <unistd.h> #include <stdlib.h> #include <errno.h> //Prototype void handle_client(int connect_fd); int main() { int server_sockfd, client_sockfd; socklen_t server_len, client_len; struct sockaddr_in server_address; struct sockaddr_in client_address; server_sockfd = socket(AF_INET, SOCK_STREAM, 0); server_address.sin_family = AF_INET; server_address.sin_addr.s_addr = htonl(INADDR_ANY); server_address.sin_port = htons(9734); server_len = sizeof(server_address); bind(server_sockfd, (struct sockaddr *)&server_address, server_len); /* Create a connection queue, ignore child exit details and wait for clients. */ listen(server_sockfd, 10); signal(SIGCHLD, SIG_IGN); while(1) { printf("server waiting\n"); client_len = sizeof(client_address); client_sockfd = accept(server_sockfd, (struct sockaddr *)&client_address, &client_len); if(fork() == 0) handle_client(client_sockfd); else close(client_sockfd); } } void handle_client(int connect_fd) { const char* remsh = "<remsh>\n"; const char* ready = "<ready>\n"; const char* ok = "<ok>\n"; const char* command = "<command>\n"; const char* complete = "<\377\n"; const char* shared_secret = "<shapoopi>\n"; static char server_msg[201]; static char client_msg[201]; static char commands[201]; int sys_return; //memset client_msg, server_msg, commands memset(&client_msg, 0, sizeof(client_msg)); memset(&server_msg, 0, sizeof(client_msg)); memset(&commands, 0, sizeof(commands)); //read remsh from client read(connect_fd, &client_msg, 200); //check remsh validity from client if(strcmp(client_msg, remsh) != 0) { errno++; perror("Error Establishing Handshake"); close(connect_fd); exit(1); } //memset client_msg memset(&client_msg, 0, sizeof(client_msg)); //write remsh to client write(connect_fd, remsh, strlen(remsh)); //read shared_secret from client read(connect_fd, &client_msg, 200); //check shared_secret validity from client if(strcmp(client_msg, shared_secret) != 0) { errno++; perror("Invalid Security Passphrase"); write(connect_fd, "no", 2); close(connect_fd); exit(1); } //memset client_msg memset(&client_msg, 0, sizeof(client_msg)); //write ok to client write(connect_fd, ok, strlen(ok)); // dup2 STDOUT_FILENO <= client fd, STDERR_FILENO <= client fd dup2(connect_fd, STDOUT_FILENO); dup2(connect_fd, STDERR_FILENO); //begin while... while read (client_msg) from server and >0 while(read(connect_fd, &client_msg, 200) > 0) { //check command validity from client if(strcmp(client_msg, command) != 0) { errno++; perror("Error, unable to retrieve data"); close(connect_fd); exit(1); } //memset client_msg memset(&client_msg, 0, sizeof(client_msg)); //write ready to client write(connect_fd, ready, strlen(ready)); //read commands from client read(connect_fd, &commands, 200); //run commands using system( ) sys_return = system(commands); //check success of system( ) if(sys_return < 0) { perror("Invalid Commands"); errno++; } //memset commands memset(commands, 0, sizeof(commands)); //write complete to client write(connect_fd, complete, sizeof(complete)); } } TCP CLIENT CODE #include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <string.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <stdlib.h> #include <errno.h> #include "readline.c" int main(int argc, char *argv[]) { int sockfd; int len; struct sockaddr_in address; int result; const char* remsh = "<remsh>\n"; const char* ready = "<ready>\n"; const char* ok = "<ok>\n"; const char* command = "<command>\n"; const char* complete = "<\377\n"; const char* shared_secret = "<shapoopi>\n"; static char server_msg[201]; static char client_msg[201]; memset(&client_msg, 0, sizeof(client_msg)); memset(&server_msg, 0, sizeof(server_msg)); /* Create a socket for the client. */ sockfd = socket(AF_INET, SOCK_STREAM, 0); /* Name the socket, as agreed with the server. */ memset(&address, 0, sizeof(address)); address.sin_family = AF_INET; address.sin_addr.s_addr = inet_addr(argv[1]); address.sin_port = htons(9734); len = sizeof(address); /* Now connect our socket to the server's socket. */ result = connect(sockfd, (struct sockaddr *)&address, len); if(result == -1) { perror("ACCESS DENIED"); exit(1); } //write remsh to server write(sockfd, remsh, strlen(remsh)); //read remsh from server read(sockfd, &server_msg, 200); //check remsh validity from server if(strcmp(server_msg, remsh) != 0) { errno++; perror("Error Establishing Initial Handshake"); close(sockfd); exit(1); } //memset server_msg memset(&server_msg, 0, sizeof(server_msg)); //write shared secret text to server write(sockfd, shared_secret, strlen(shared_secret)); //read ok from server read(sockfd, &server_msg, 200); //check ok velidity from server if(strcmp(server_msg, ok) != 0 ) { errno++; perror("Incorrect security phrase"); close(sockfd); exit(1); } //? dup2 STDIN_FILENO = server socket fd? //dup2(sockfd, STDIN_FILENO); //begin while(1)/////////////////////////////////////// while(1){ //memset both msg arrays memset(&client_msg, 0, sizeof(client_msg)); memset(&server_msg, 0, sizeof(server_msg)); //print Enter Command, scan input, fflush to stdout printf("<<Enter Command>> "); scanf("%s", client_msg); fflush(stdout); //check quit input, if true close and exit successfully if(strcmp(client_msg, "quit") == 0) { printf("Exiting\n"); close(sockfd); exit(EXIT_SUCCESS); } //write command to server write(sockfd, command, strlen(command)); //read ready from server read(sockfd, &server_msg, 200); //check ready validity from server if(strcmp(server_msg, ready) != 0) { errno++; perror("Failed Server Communications"); close(sockfd); exit(1); } //memset server_msg memset(&server_msg, 0, sizeof(server_msg)); //begin looping and retrieving from stdin, //break loop at EOF or complete while((read(sockfd, server_msg, 200) != 0) && (strcmp(server_msg, complete) != 0)) { //while((fgets(server_msg, 4096, stdin) != EOF) || (strcmp(server_msg, complete) == 0)) { printf("%s", server_msg); memset(&server_msg, 0, sizeof(server_msg)); } } }

    Read the article

  • UNIX pipes on C block on read

    - by Toni Cárdenas
    I'm struggling to implement a shell with pipelines for class. typedef struct { char** cmd; int in[2]; int out[2]; } cmdio; cmdio cmds[MAX_PIPE + 1]; Commands in the pipeline are read and stored in cmds. cmdio[i].in is the pair of file descriptors of the input pipe returned by pipe(). For the first command, which reads from terminal input, it is just {fileno(stdin), -1}. cmdin[i].outis similar for the output pipe/terminal output. cmdio[i].in is the same as cmd[i-1].out. For example: $ ls -l | sort | wc CMD: ls -l IN: 0 -1 OUT: 3 4 CMD: sort IN: 3 4 OUT: 5 6 CMD: wc IN: 5 6 OUT: -1 1 We pass each command to process_command, which does a number of things: for (cmdi = 0; cmds[cmdi].cmd != NULL; cmdi++) { process_command(&cmds[cmdi]); } Now, inside process_command: if (!(pid_fork = fork())) { dup2(cmd->in[0], fileno(stdin)); dup2(cmd->out[1], fileno(stdout)); if (cmd->in[1] >= 0) { if (close(cmd->in[1])) { perror(NULL); } } if (cmd->out[0] >= 0) { if (close(cmd->out[0])) { perror(NULL); } } execvp(cmd->cmd[0], cmd->cmd); exit(-1); } The problem is that reading from the pipe blocks forever: COMMAND $ ls | wc Created pipe, in: 5 out: 6 Foreground pid: 9042, command: ls, Exited, info: 0 [blocked running read() within wc] If, instead of exchanging the process with execvp, I just do this: if (!(pid_fork = fork())) { dup2(cmd->in[0], fileno(stdin)); dup2(cmd->out[1], fileno(stdout)); if (cmd->in[1] >= 0) { if (close(cmd->in[1])) { perror(NULL); } } if (cmd->out[0] >= 0) { if (close(cmd->out[0])) { perror(NULL); } } char buf[6]; read(fileno(stdin), buf, 5); buf[5] = '\0'; printf("%s\n", buf); exit(0); } It happens to work: COMMAND $ cmd1 | cmd2 | cmd3 | cmd4 | cmd5 Pipe creada, in: 11 out: 12 Pipe creada, in: 13 out: 14 Pipe creada, in: 15 out: 16 Pipe creada, in: 17 out: 18 hola! Foreground pid: 9251, command: cmd1, Exited, info: 0 Foreground pid: 9252, command: cmd2, Exited, info: 0 Foreground pid: 9253, command: cmd3, Exited, info: 0 Foreground pid: 9254, command: cmd4, Exited, info: 0 hola! Foreground pid: 9255, command: cmd5, Exited, info: 0 What could be the problem?

    Read the article

  • forkpty - socket

    - by Alexxx
    Hi, I'm trying to develop a simple "telnet/server" daemon which have to run a program on a new socket connection. This part working fine. But I have to associate my new process to a pty, because this process have some terminal capabilities (like a readline). The code I've developped is (where socketfd is the new socket file descriptor for the new input connection) : int masterfd, pid; const char *prgName = "..."; char *arguments[10] = ....; if ((pid = forkpty(&masterfd, NULL, NULL, NULL)) < 0) perror("FORK"); else if (pid) return pid; else { close(STDOUT_FILENO); dup2(socketfd, STDOUT_FILENO); close(STDIN_FILENO); dup2(socketfd, STDIN_FILENO); close(STDERR_FILENO); dup2(socketfd, STDERR_FILENO); if (execvp(prgName, arguments) < 0) { perror("execvp"); exit(2); } } With that code, the stdin / stdout / stderr file descriptor of my "prgName" are associated to the socket (when looking with ls -la /proc/PID/fd), and so, the terminal capabilities of this process doesn't work. A test with a connection via ssh/sshd on the remote device, and executing "localy" (under the ssh connection) prgName, show that the stdin/stdout/stderr fd of this process "prgName" are associated to a pty (and so the terminal capabilities of this process are working fine). What I am doing wrong? How to associate my socketfd with the pty (created by forkpty) ? Thank Alex

    Read the article

  • Why do I need to close fds when reading and writing to the pipe?

    - by valentimsousa
    However, what if one of my processes needs to continuously write to the pipe while the other pipe needs to read? This example seems to work only for one write and one read. I need multi read and write void executarComandoURJTAG(int newSock) { int input[2], output[2], estado, d; pid_t pid; char buffer[256]; char linha[1024]; pipe(input); pipe(output); pid = fork(); if (pid == 0) {// child close(0); close(1); close(2); dup2(input[0], 0); dup2(output[1], 1); dup2(output[1], 2); close(input[1]); close(output[0]); execlp("jtag", "jtag", NULL); } else { // parent close(input[0]); close(output[1]); do { read(newSock, linha, 1024); /* Escreve o buffer no pipe */ write(input[1], linha, strlen(linha)); close(input[1]); while ((d = read(output[0], buffer, 255))) { //buffer[d] = '\0'; write(newSock, buffer, strlen(buffer)); puts(buffer); } write(newSock, "END", 4); } while (strcmp(linha, "quit") != 0); } }

    Read the article

  • Bad File descriptor

    - by Luke
    Does anyone see a problem with this, its not working saying bad file descriptor not sure why? pipe(pipefd[0]); if ((opid = fork()) == 0) { dup2(pipefd[0][1],1);/*send to output*/ close(pipefd[0][0]); close(pipefd[0][1]); execlp("ls","ls","-al",NULL); } if((cpid = fork())==0){ dup2(pipefd[0][1],0);/*read from input*/ close(pipefd[0][0]); close(pipefd[1][1]); execlp("grep","grep",".bak",NULL); } close(pipefd[0][0]); close(pipefd[0][1]);

    Read the article

  • Unix Piping using Fork and Dup

    - by Jacob
    Lets say within my program I want to execute two child processes, one to to execute a "ls -al" command and then pipe that into "wc" command and display the output on the terminal. How can I do this using pipe file descriptors so far the code I have written: An example would be greatly helpful int main(int argc, char *argv[]) { int pipefd[2] pipe(pipefd2); if ((fork()) == 0) { dup2(pipefd2[1],STDOUT_FILENO); close(pipefd2[0]); close(pipefd2[1]); execl("ls", "ls","-al", NULL); exit(EXIT_FAILURE); } if ((fork()) == 0){ dup2(pipefd2[0],STDIN_FILENO); close(pipefd2[0]); close(pipefd2[1]); execl("/usr/bin/wc","wc",NULL); exit(EXIT_FAILURE); } close(pipefd[0]); close(pipefd[1]); close(pipefd2[0]); close(pipefd2[1]); }

    Read the article

  • Redirecting one file to another using dub2 and strtok

    - by Sergiy Zakharov
    OK, here goes. I have to write a program, in which I need to use strtok and dup2 to redirect one file to another, but I need to also have the user to actually put the command cat < file1 file2, but not from the shell, but instead by using my program. That's why I need strtok. And the reason my program doesn't work is probably because of that, because I don't really understand how strtok works. I found a similar program on the internet, but they just take the ls command and redirect it to the file. That's it. My program is much more complicated. I mean, it would've been easier just to say in shell cat < file1 file2, but for some reason they want us to do it this way. So, anyways, here is what I have so far (here I just combined what I have found on the internet with what I already had from before. We had to do something similar but then the user would just go ls or ls -l. Very simple stuff. This is much harder, for me, at least.) #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <errno.h> #include <sys/wait.h> #include <string.h> int main() { pid_t pid; char line[256]; char *args[129]; int i; int fd; int status; char *temp; while (1) { printf(">"); if (fgets(line, 256, stdin) == 0) { exit(0); } else { pid = fork(); if (pid == 0) { i = 0; temp = strtok("<",line); while (temp != NULL) { args[i++] = temp; temp = strtok(">",line); args[i] = '\0'; } fd = open("hello", O_RDONLY); dup2(fd, STDIN_FILENO); fd = open("world", O_WRONLY|O_CREAT|O_TRUNC, S_IRWXU); dup2(fd, STDOUT_FILENO ); close(fd); execvp(args[0], args); } else { close(fd); wait(&status); } } } } Any help would be greatly appreciated.

    Read the article

  • How do you play or record audio (to .WAV) on Linux in C++? [closed]

    - by Jacky Alcine
    Hello, I've been looking for a way to play and record audio on a Linux (preferably Ubuntu) system. I'm currently working on a front-end to a voice recognition toolkit that'll automate a few steps required to adapt a voice model for PocketSphinx and Julius. Suggestions of alternative means of audio input/output are welcome, as well as a fix to the bug shown below. Here is the current code I've used so far to play a .WAV file: void Engine::sayText ( const string OutputText ) { string audioUri = "temp.wav"; string requestUri = this->getRequestUri( OPENMARY_PROCESS , OutputText.c_str( ) ); int error , audioStream; pa_simple *pulseConnection; pa_sample_spec simpleSpecs; simpleSpecs.format = PA_SAMPLE_S16LE; simpleSpecs.rate = 44100; simpleSpecs.channels = 2; eprintf( E_MESSAGE , "Generating audio for '%s' from '%s'..." , OutputText.c_str( ) , requestUri.c_str( ) ); FILE* audio = this->getHttpFile( requestUri , audioUri ); fclose(audio); eprintf( E_MESSAGE , "Generated audio."); if ( ( audioStream = open( audioUri.c_str( ) , O_RDONLY ) ) < 0 ) { fprintf( stderr , __FILE__": open() failed: %s\n" , strerror( errno ) ); goto finish; } if ( dup2( audioStream , STDIN_FILENO ) < 0 ) { fprintf( stderr , __FILE__": dup2() failed: %s\n" , strerror( errno ) ); goto finish; } close( audioStream ); pulseConnection = pa_simple_new( NULL , "AudioPush" , PA_STREAM_PLAYBACK , NULL , "openMary C++" , &simpleSpecs , NULL , NULL , &error ); for (int i = 0;;i++ ) { const int bufferSize = 1024; uint8_t audioBuffer[bufferSize]; ssize_t r; eprintf( E_MESSAGE , "Buffering %d..",i); /* Read some data ... */ if ( ( r = read( STDIN_FILENO , audioBuffer , sizeof (audioBuffer ) ) ) <= 0 ) { if ( r == 0 ) /* EOF */ break; eprintf( E_ERROR , __FILE__": read() failed: %s\n" , strerror( errno ) ); if ( pulseConnection ) pa_simple_free( pulseConnection ); } /* ... and play it */ if ( pa_simple_write( pulseConnection , audioBuffer , ( size_t ) r , &error ) < 0 ) { fprintf( stderr , __FILE__": pa_simple_write() failed: %s\n" , pa_strerror( error ) ); if ( pulseConnection ) pa_simple_free( pulseConnection ); } usleep(2); } /* Make sure that every single sample was played */ if ( pa_simple_drain( pulseConnection , &error ) < 0 ) { fprintf( stderr , __FILE__": pa_simple_drain() failed: %s\n" , pa_strerror( error ) ); if ( pulseConnection ) pa_simple_free( pulseConnection ); } } NOTE: If you want the rest of the code to this file, you can download it here directly from Launchpad.

    Read the article

  • problem with piping in my own implementation of shell

    - by codemax
    Hey guys, i am implementing my own shell. I want to involve piping. i searched here and i got a code. But it is not working.Can any one help me? this is my code #include <sys/types.h> #include <sys/wait.h> #include <sys/ipc.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <iostream> #include <cstdlib> using namespace std; char temp1[81][81],temp2[81][81] ,*cmdptr1[40], *cmdptr2[40]; void process(char**,int); int arg_count, count; int arg_cnt[2]; int pip,tok; char input[81]; int fds[2]; void process( char* cmd[])//, int arg_count ) { pid_t pid; pid = fork(); //char path[81]; //getcwd(path,81); //strcat(path,"/"); //strcat(path,cmd[0]); if(pid < 0) { cout << "Fork Failed" << endl; exit(-1); } else if( pid == 0 ) { execvp( cmd[0] , cmd ); } else { wait(NULL); } } void pipe(char **cmd1, char**cmd2) { cout<<endl<<endl<<"in pipe"<<endl; for(int i=0 ; i<arg_cnt[0] ; i++) { cout<<cmdptr1[i]<<" "; } cout<<endl; for(int i=0 ; i<arg_cnt[1] ; i++) { cout<<cmdptr2[i]<<" "; } pipe(fds); if (fork() == 0 ) { dup2(fds[1], 1); close(fds[0]); close(fds[1]); process(cmd1); } if (fork() == 0) { dup2(fds[0], 0); close(fds[0]); close(fds[1]); process(cmd2); } close(fds[0]); close(fds[1]); wait(NULL); } void pipecommand(char** cmd1, char** cmd2) { cout<<endl<<endl; for(int i=0 ; i<arg_cnt[0] ; i++) { cout<<cmd1[i]<<" "; } cout<<endl; for(int i=0 ; i<arg_cnt[1] ; i++) { cout<<cmd2[i]<<" "; } int fds[2]; // file descriptors pipe(fds); // child process #1 if (fork() == 0) { // Reassign stdin to fds[0] end of pipe. dup2(fds[0], STDIN_FILENO); close(fds[1]); close(fds[0]); process(cmd2); // child process #2 if (fork() == 0) { // Reassign stdout to fds[1] end of pipe. dup2(fds[1], STDOUT_FILENO); close(fds[0]); close(fds[1]); // Execute the first command. process(cmd1); } wait(NULL); } close(fds[1]); close(fds[0]); wait(NULL); } void splitcommand1() { tok++; int k,done=0,no=0; arg_count = 0; for(int i=count ; input[i] != '\0' ; i++) { k=0; while(1) { count++; if(input[i] == ' ') { break; } if((input[i] == '\0')) { done = 1; break; } if(input[i] == '|') { pip = 1; done = 1; break; } temp1[arg_count][k++] = input[i++]; } temp1[arg_count][k++] = '\0'; arg_count++; if(done == 1) { break; } } for(int i=0 ; i<arg_count ; i++) { cmdptr1[i] = temp1[i]; } arg_cnt[tok] = arg_count; } void splitcommand2() { tok++; cout<<"count is :"<<count<<endl; int k,done=0,no=0; arg_count = 0; for(int i=count ; input[i] != '\0' ; i++) { k=0; while(1) { count++; if(input[i] == ' ') { break; } if((input[i] == '\0')) { done = 1; break; } if(input[i] == '|') { pip = 1; done = 1; cout<<"PIP"; break; } temp2[arg_count][k++] = input[i++]; } temp2[arg_count][k++] = '\0'; arg_count++; if(done == 1) { break; } } for(int i=0 ; i<arg_count ; i++) { cmdptr2[i] = temp2[i]; } arg_cnt[tok] = arg_count; } int main() { cout<<endl<<endl<<"Welcome to unique shell !!!!!!!!!!!"<<endl; tok=-1; while(1) { cout<<endl<<"***********UNIQUE**********"<<endl; cin.getline(input,81); count = 0,pip=0; splitcommand1(); if(pip == 1) { count++; splitcommand2(); } cout<<endl<<endl; if(strcmp(cmdptr1[0], "exit") == 0 ) { cout<<endl<<"EXITING UNIQUE SHELL"<<endl; exit(0); } //cout<<endl<<"Arg count is :"<<arg_count<<endl; if(pip == 1) { cout<<endl<<endl<<"in main :"; for(int i=0 ; i<arg_cnt[0] ; i++) { cout<<cmdptr1[i]<<" "; } cout<<endl; for(int i=0 ; i<arg_cnt[1] ; i++) { cout<<cmdptr2[i]<<" "; } pipe(cmdptr1, cmdptr2); } else { process (cmdptr1);//,arg_count); } } } I know it is not well coded. But try to help me :(

    Read the article

  • how to implement word count bash shell

    - by codemax
    hey guys. I am trying to write my own code for the word count in bash shell. I did usual way. But i wanna use pipe's output to count the word. So for eg the 1st command is cat and i am redirecting to a file called med. Now i have to use to 'dup2' function to count the words in that file. How can i write the code for my wc? This is the code for my shell pgm : void process( char* cmd[], int arg_count ) { pid_t pid; pid = fork(); char path[81]; getcwd(path,81); strcat(path,"/"); strcat(path,cmd[0]); if(pid < 0) { cout << "Fork Failed" << endl; exit(-1); } else if( pid == 0 ) { int fd; fd =open("med", O_RDONLY); dup2(fd ,0); execvp( path, cmd ); } else { wait(NULL); } } And my wordcount is : int main(int argc, char *argv[]) { char ch; int count = 0; ifstream infile(argv[1]); while(!infile.eof()) { infile.get(ch); if(ch == ' ') { count++; } } return 0; } I dont know how to do input redirection i want my code to do this : When i just type wordcount in my shell implementation, I want it to count the words in the med file by default. Thanks in advance

    Read the article

  • can't read from stream until child exits?

    - by BobTurbo
    OK I have a program that creates two pipes - forks - the child's stdin and stdout are redirected to one end of each pipe - the parent is connected to the other ends of the pipes and tries to read the stream associated with the child's output and print it to the screen (and I will also make it write to the input of the child eventually). The problem is, when the parent tries to fgets the child's output stream, it just stalls and waits until the child dies to fgets and then print the output. If the child doesn't exit, it just waits forever. What is going on? I thought that maybe fgets would block until SOMETHING was in the stream, but not block all the way until the child gives up its file descriptors. Here is the code: #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/types.h> #include <unistd.h> int main(int argc, char *argv[]) { FILE* fpin; FILE* fpout; int input_fd[2]; int output_fd[2]; pid_t pid; int status; char input[100]; char output[100]; char *args[] = {"/somepath/someprogram", NULL}; fgets(input, 100, stdin); // the user inputs the program name to exec pipe(input_fd); pipe(output_fd); pid = fork(); if (pid == 0) { close(input_fd[1]); close(output_fd[0]); dup2(input_fd[0], 0); dup2(output_fd[1], 1); input[strlen(input)-1] = '\0'; execvp(input, args); } else { close(input_fd[0]); close(output_fd[1]); fpin = fdopen(input_fd[1], "w"); fpout = fdopen(output_fd[0], "r"); while(!feof(fpout)) { fgets(output, 100, fpout); printf("output: %s\n", output); } } return 0; }

    Read the article

  • create backup file descriptor?

    - by BobTurbo
    stdinBackup = 4; dup2(0, stdinBackup); Currently I am doing the above to 'backup' stdin so that it can be restored from backup later after it has been redirected somewhere else. I have a feeling that I am doing a lot wrong? (eg arbitrarily assigning 4 is surely not right). Anyone point me in the right direction?

    Read the article

  • Perl, redirect stdout to file

    - by Mike
    I'm looking for an example of redirecting stdout to a file using Perl. I'm doing a fairly straightforward fork/exec tool, and I want to redirect the child's output to a file instead of the parents stdout. Is there an equivilant of dup2() I should use? I can't seem to find it

    Read the article

  • How can I pre-authorize authopen?

    - by Georg
    I'm using authopen inside one of my programs to modify files owned by root. As can be seen in the screenshot below authopen asks for a admin password. What I'd like to achieve is that the dialog shows my app's name and then passes the authorization to authopen. Code Launching authopen which returns an authorized file descriptor. int pipe[2]; socketpair(AF_UNIX, SOCK_STREAM, 0, pipe); if (fork() == 0) { // child // close parent's pipe close(pipe[0]); dup2(pipe[1], STDOUT_FILENO); const char *authopenPath = "/usr/libexec/authopen"; execl(authopenPath, authopenPath, "-stdoutpipe", [self.device.devicePath fileSystemRepresentation], NULL); NSLog(@"Fatal error, quitting."); exit(-1); } // parent // close childs's pipe close(pipe[1]); // get file descriptor through sockets I'd really like not to use AuthorizationExecuteWithPrivileges because then I'd have to get more rights than I want to.

    Read the article

  • Pipe implementation

    - by nunos
    I am trying to implement a linux shell that supports piping. I have already done simple commands, commands running in background, redirections, but piping is still missing. I have already read about it and seen some snippets of code, but still haven't been able to sort out a working solution. What I have so far: int fd[2]; pid_t pid = fork(); if (pid == -1) return -1; if (pid == 0) { dup2(0, fd[0]); execlp("sort", "sort", NULL); } I am a novice programmer, as you can probably tell, and when I am programming something I don't know much about, this being obviously the case, I like to start with something really easy and concrete and then build from there. So, before being able to implement three and more different commands in pipeline, I would like to be able to compute "ls names.txt | sort" or something similiar, in which names.txt is a file of names alfabetically unordered. Thanks.

    Read the article

  • What to do if exec() fails?

    - by Grigory
    Let's suppose we have a code doing something like this: int pipes[2]; pipe(pipes); pid_t p = fork(); if(0 == p) { dup2(pipes[1], STDOUT_FILENO); execv("/path/to/my/program", NULL); ... } else { //... parent process stuff } As you can see, it's creating a pipe, forking and using the pipe to read the child's output (I can't use popen here, because I also need the PID of the child process for other purposes). Question is, what should happen if in the above code, execv fails? Should I call exit() or abort()? As far as I know, those functions close the open file descriptors. Since fork-ed process inherits the parent's file descriptors, does it mean that the file descriptors used by the parent process will become unusable?

    Read the article

  • Is there a c++ library that provides functionality to execute an external program and read its outpu

    - by BD at Rivenhill
    Basically, I'm looking for something that will allow me to replicate the following Perl code: my $fh = new FileHandle; $fh->open("foo |"); while (<$fh>) { # Do something with this line of data. } This is in the context of Linux, so a library that is specific to Windows will not help. I know how to write a program that does fork/exec/dup2 and all that basic shell-type jazz, but there are some fiddly details involving terminals that I don't feel like messing around with (and I don't have a copy of "Advanced Programming in the UNIX Environment" or a similar reference handy), so I'm hoping that someone has already solved this problem.

    Read the article

  • error while installing the libmemcached

    - by Ahmet vardar
    I get this while installing libmemcached root@server [/libmemcached]# make make all-am make[1]: Entering directory `/libmemcached' if /bin/sh ./libtool --tag=CXX --mode=compile g++ -DHAVE_CONFIG_H -I. -I. -I. -I. -I. -ggdb -DBUILDING_HASHKIT -MT libhashkit/libhashkit_libhashkit_la-aes.lo -MD -MP -MF "libhashkit/.deps/libhashkit_libhashkit_la-aes.Tpo" -c -o libhashkit/libhashkit_libhashkit_la-aes.lo `test -f 'libhashkit/aes.cc' || echo './'`libhashkit/aes.cc; \ then mv -f "libhashkit/.deps/libhashkit_libhashkit_la-aes.Tpo" "libhashkit/.deps/libhashkit_libhashkit_la-aes.Plo"; else rm -f "libhashkit/.deps/libhashkit_libhashkit_la-aes.Tpo"; exit 1; fi ./libtool: line 866: X--tag=CXX: command not found ./libtool: line 899: libtool: ignoring unknown tag : command not found ./libtool: line 866: X--mode=compile: command not found ./libtool: line 1032: *** Warning: inferring the mode of operation is deprecated.: command not found ./libtool: line 1033: *** Future versions of Libtool will require --mode=MODE be specified.: command not found ./libtool: line 1176: Xg++: command not found ./libtool: line 1176: X-DHAVE_CONFIG_H: command not found ./libtool: line 1176: X-I.: command not found ./libtool: line 1176: X-I.: command not found ./libtool: line 1176: X-I.: command not found ./libtool: line 1176: X-I.: command not found ./libtool: line 1176: X-I.: command not found ./libtool: line 1176: X-ggdb: command not found ./libtool: line 1176: X-DBUILDING_HASHKIT: command not found ./libtool: line 1176: X-MT: command not found ./libtool: line 1176: Xlibhashkit/libhashkit_libhashkit_la-aes.lo: No such file or directory ./libtool: line 1176: X-MD: command not found ./libtool: line 1176: X-MP: command not found ./libtool: line 1176: X-MF: command not found ./libtool: line 1176: Xlibhashkit/.deps/libhashkit_libhashkit_la-aes.Tpo: No such file or directory ./libtool: line 1176: X-c: command not found ./libtool: line 1228: Xlibhashkit/libhashkit_libhashkit_la-aes.lo: No such file or directory ./libtool: line 1233: libtool: compile: cannot determine name of library object from `': command not found make[1]: *** [libhashkit/libhashkit_libhashkit_la-aes.lo] Error 1 make[1]: Leaving directory `/libmemcached' make: *** [all] Error 2 OUTPUT OF ./configure checking build system type... x86_64-unknown-linux-gnu checking host system type... x86_64-unknown-linux-gnu checking target system type... x86_64-unknown-linux-gnu checking for a BSD-compatible install... /usr/bin/install -c checking whether build environment is sane... yes checking for gawk... gawk checking whether make sets $(MAKE)... yes checking for style of include used by make... GNU checking for gcc... gcc checking whether the C compiler works... yes checking for C compiler default output file name... a.out checking for suffix of executables... checking whether we are cross compiling... no checking for suffix of object files... o checking whether we are using the GNU C compiler... yes checking whether gcc accepts -g... yes checking for gcc option to accept ISO C89... none needed checking dependency style of gcc... gcc3 checking dependency style of gcc... (cached) gcc3 checking how to run the C preprocessor... gcc -E checking for grep that handles long lines and -e... /bin/grep checking for egrep... /bin/grep -E checking for ANSI C header files... yes checking for sys/types.h... yes checking for sys/stat.h... yes checking for stdlib.h... yes checking for string.h... yes checking for memory.h... yes checking for strings.h... yes checking for inttypes.h... yes checking for stdint.h... yes checking for unistd.h... yes checking minix/config.h usability... no checking minix/config.h presence... no checking for minix/config.h... no checking whether it is safe to define __EXTENSIONS__... yes checking for isainfo... no checking for g++... g++ checking whether we are using the GNU C++ compiler... yes checking whether g++ accepts -g... yes checking dependency style of g++... gcc3 checking dependency style of g++... (cached) gcc3 checking whether gcc and cc understand -c and -o together... yes checking how to create a ustar tar archive... gnutar checking whether __SUNPRO_C is declared... no checking whether __ICC is declared... no checking "C Compiler version--yes"... "gcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-52)" checking "C++ Compiler version"... "g++ (GCC) 4.1.2 20080704 (Red Hat 4.1.2-52)" checking whether time.h and sys/time.h may both be included... yes checking whether struct tm is in sys/time.h or time.h... time.h checking for size_t... yes checking for special C compiler options needed for large files... no checking for _FILE_OFFSET_BITS value needed for large files... no checking for library containing clock_gettime... -lrt checking sys/socket.h usability... yes checking sys/socket.h presence... yes checking for sys/socket.h... yes checking size of off_t... 8 checking size of size_t... 8 checking size of long long... 8 checking if time_t is unsigned... no checking for setsockopt... yes checking for bind... yes checking whether the compiler provides atomic builtins... yes checking assert.h usability... yes checking assert.h presence... yes checking for assert.h... yes checking whether to enable assertions... yes checking whether it is safe to use -fdiagnostics-show-option... yes checking whether it is safe to use -floop-parallelize-all... no checking whether it is safe to use -Wextra... yes checking whether it is safe to use -Wformat... yes checking whether it is safe to use -Wconversion... no checking whether it is safe to use -Wmissing-declarations from C++... no checking whether it is safe to use -Wframe-larger-than... no checking whether it is safe to use -Wlogical-op... no checking whether it is safe to use -Wredundant-decls from C++... yes checking whether it is safe to use -Wattributes from C++... no checking whether it is safe to use -Wno-attributes... no checking for perl... perl checking for dpkg-gensymbols... no checking for lcov... no checking for genhtml... no checking for sphinx-build... no checking for working -pipe... yes checking for bison... bison checking for flex... flex checking how to print strings... printf checking for a sed that does not truncate output... /bin/sed checking for fgrep... /bin/grep -F checking for ld used by gcc... /usr/bin/ld checking if the linker (/usr/bin/ld) is GNU ld... yes checking for BSD- or MS-compatible name lister (nm)... /usr/bin/nm -B checking the name lister (/usr/bin/nm -B) interface... BSD nm checking whether ln -s works... yes checking the maximum length of command line arguments... 98304 checking whether the shell understands some XSI constructs... yes checking whether the shell understands "+="... yes checking how to convert x86_64-unknown-linux-gnu file names to x86_64-unknown-linux-gnu format... func_convert_file_noop checking how to convert x86_64-unknown-linux-gnu file names to toolchain format... func_convert_file_noop checking for /usr/bin/ld option to reload object files... -r checking for objdump... objdump checking how to recognize dependent libraries... pass_all checking for dlltool... no checking how to associate runtime and link libraries... printf %s\n checking for ar... ar checking for archiver @FILE support... @ checking for strip... strip checking for ranlib... ranlib checking command to parse /usr/bin/nm -B output from gcc object... ok checking for sysroot... no checking for mt... no checking if : is a manifest tool... no checking for dlfcn.h... yes checking for objdir... .libs checking if gcc supports -fno-rtti -fno-exceptions... no checking for gcc option to produce PIC... -fPIC -DPIC checking if gcc PIC flag -fPIC -DPIC works... yes checking if gcc static flag -static works... yes checking if gcc supports -c -o file.o... yes checking if gcc supports -c -o file.o... (cached) yes checking whether the gcc linker (/usr/bin/ld -m elf_x86_64) supports shared libraries... yes checking whether -lc should be explicitly linked in... no checking dynamic linker characteristics... GNU/Linux ld.so checking how to hardcode library paths into programs... immediate checking whether stripping libraries is possible... yes checking if libtool supports shared libraries... yes checking whether to build shared libraries... yes checking whether to build static libraries... yes checking how to run the C++ preprocessor... g++ -E checking for ld used by g++... /usr/bin/ld -m elf_x86_64 checking if the linker (/usr/bin/ld -m elf_x86_64) is GNU ld... yes checking whether the g++ linker (/usr/bin/ld -m elf_x86_64) supports shared libraries... yes checking for g++ option to produce PIC... -fPIC -DPIC checking if g++ PIC flag -fPIC -DPIC works... yes checking if g++ static flag -static works... yes checking if g++ supports -c -o file.o... yes checking if g++ supports -c -o file.o... (cached) yes checking whether the g++ linker (/usr/bin/ld -m elf_x86_64) supports shared libraries... yes checking dynamic linker characteristics... (cached) GNU/Linux ld.so checking how to hardcode library paths into programs... immediate checking whether the -Werror option is usable... yes checking for simple visibility declarations... yes checking for ISO C++ 98 include files... checking whether memcached executable path has been provided... no checking for memcached... /usr/local/bin/memcached checking whether memcached_sasl executable path has been provided... no checking for memcached_sasl... no checking whether gearmand executable path has been provided... no checking for gearmand... no checking libgearman/gearmand.h usability... no checking libgearman/gearmand.h presence... no checking for libgearman/gearmand.h... no checking for library containing getopt_long... none required checking for library containing gethostbyname... none required checking for the pthreads library -lpthreads... no checking whether pthreads work without any flags... yes checking for joinable pthread attribute... PTHREAD_CREATE_JOINABLE checking if more special flags are required for pthreads... no checking for PTHREAD_PRIO_INHERIT... yes checking the location of cstdint... configure: WARNING: Could not find a cstdint header. <stdint.h> checking the location of cinttypes... configure: WARNING: Could not find a cinttypes header. <inttypes.h> checking whether byte ordering is bigendian... no checking for htonll... no checking for working SO_SNDTIMEO... yes checking for working SO_RCVTIMEO... yes checking for supported struct padding... yes checking for alarm... yes checking for dup2... yes checking for getline... yes checking for gettimeofday... yes checking for memchr... yes checking for memmove... yes checking for memset... yes checking for pipe2... no checking for select... yes checking for setenv... yes checking for socket... yes checking for sqrt... yes checking for strcasecmp... yes checking for strchr... yes checking for strdup... yes checking for strerror... yes checking for strtol... yes checking for strtoul... yes checking for strtoull... yes checking arpa/inet.h usability... yes checking arpa/inet.h presence... yes checking for arpa/inet.h... yes checking fcntl.h usability... yes checking fcntl.h presence... yes checking for fcntl.h... yes checking libintl.h usability... yes checking libintl.h presence... yes checking for libintl.h... yes checking limits.h usability... yes checking limits.h presence... yes checking for limits.h... yes checking malloc.h usability... yes checking malloc.h presence... yes checking for malloc.h... yes checking netdb.h usability... yes checking netdb.h presence... yes checking for netdb.h... yes checking netinet/in.h usability... yes checking netinet/in.h presence... yes checking for netinet/in.h... yes checking stddef.h usability... yes checking stddef.h presence... yes checking for stddef.h... yes checking sys/time.h usability... yes checking sys/time.h presence... yes checking for sys/time.h... yes checking execinfo.h usability... yes checking execinfo.h presence... yes checking for execinfo.h... yes checking cxxabi.h usability... yes checking cxxabi.h presence... yes checking for cxxabi.h... yes checking sys/sysctl.h usability... yes checking sys/sysctl.h presence... yes checking for sys/sysctl.h... yes checking umem.h usability... no checking umem.h presence... no checking for umem.h... no checking for C++ compiler vendor... gnu checking for working alloca.h... yes checking for alloca... yes checking for error_at_line... yes checking for pid_t... yes checking vfork.h usability... no checking vfork.h presence... no checking for vfork.h... no checking for fork... yes checking for vfork... yes checking for working fork... yes checking for working vfork... (cached) yes checking for stdlib.h... (cached) yes checking for GNU libc compatible malloc... yes checking for stdlib.h... (cached) yes checking for GNU libc compatible realloc... yes checking whether strerror_r is declared... yes checking for strerror_r... yes checking whether strerror_r returns char *... yes checking for stdbool.h that conforms to C99... yes checking for _Bool... no checking for int16_t... yes checking for int32_t... yes checking for int64_t... yes checking for int8_t... yes checking for off_t... yes checking for pid_t... (cached) yes checking for ssize_t... yes checking for uint16_t... yes checking for uint32_t... yes checking for uint64_t... yes checking for uint8_t... yes checking whether byte ordering is bigendian... (cached) no checking for an ANSI C-conforming const... yes checking for inline... inline checking for working volatile... yes checking for C/C++ restrict keyword... __restrict checking whether the compiler supports GCC C++ ABI name demangling... yes checking sasl/sasl.h usability... no checking sasl/sasl.h presence... no checking for sasl/sasl.h... no checking uuid/uuid.h usability... yes checking uuid/uuid.h presence... yes checking for uuid/uuid.h... yes checking for main in -luuid... yes checking for clock_gettime in -lrt... yes checking for floor in -lm... yes checking for sigignore... yes checking atomic.h usability... no checking atomic.h presence... no checking for atomic.h... no checking for setppriv... no checking for winsock2.h... no checking for poll.h... yes checking for sys/wait.h... yes checking for fnmatch.h... yes checking for MSG_NOSIGNAL... yes checking for MSG_DONTWAIT... yes checking for MSG_MORE... yes checking event.h usability... yes checking event.h presence... yes checking for event.h... yes checking for main in -levent... yes checking for endianness... little configure: creating ./config.status config.status: creating Makefile config.status: creating docs/conf.py config.status: creating libhashkit-1.0/configure.h config.status: creating libmemcached-1.0/configure.h config.status: creating libmemcached-1.2/configure.h config.status: creating libmemcached-2.0/configure.h config.status: creating support/libmemcached.pc config.status: creating support/libmemcached.spec config.status: creating support/libmemcached-fc.spec config.status: creating libtest/version.h config.status: creating config.h config.status: config.h is unchanged config.status: executing depfiles commands config.status: executing libtool commands --- Configuration summary for libmemcached version 1.0.6 * Installation prefix: /usr/local * System type: unknown-linux-gnu * Host CPU: x86_64 * C Compiler: gcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-52) * Assertions enabled: yes * Debug enabled: no * Warnings as failure: no * SASL support: --- anyone knows how to solve this ?

    Read the article

1