/*********************************************************************
* connectPipeLine connects the process to a pipeline by redirecting
* standard input to frontfd[0] and standard output to backfd[1].
* If frontfd[0] = -1, the process is at the front of the pipeline and
* standard input may be redirected to a file. If backfd[1] = -1,
* the process is at the back of the pipeline and standard output may
* be redirected to a file. Otherwise redirection to a file is
* an error. If explicit redirection occurs in cmd, it is removed
* in processing. A 0 is returned if connectPipeLine is successful
* and a -1 is returned otherwise.
*********************************************************************/
#include "ush.h"
/********************************************************************
* Function checks redirect and calls function redirect
*/
int checkRedirect(char* cmd, int frontfd[], int backfd[])
{
int result = -1;
char* inFileName;
char* outFileName;
if (parseFile(cmd, IN_REDIRECT_SYMBOL , &inFileName) == -1)
return result;
else
if (inFileName != NULL && frontfd[0] != -1)
/* no redirection allowed at front of pipeline */
return result;
else
if (parseFile(cmd, OUT_REDIRECT_SYMBOL, &outFileName) == -1)
return result;
else
if (outFileName != NULL && backfd[1] != -1)
/* no redirection allowed at back of pipeline */
return result;
else
if (redirect(inFileName, outFileName) == -1)
return result;
return 0;
}
int connectPipeLine(char* cmd, int frontfd[], int backfd[])
{
int result = 0;
if (checkRedirect(cmd, frontfd, backfd) == -1)
result = -1;
else
{
/* now connect up appropriate pipes */
if (frontfd[0] != -1)
{
if (dup2(frontfd[0], STDIN_FILENO) == -1)
result = -1;
}
if (backfd[1] != -1)
{
if (dup2(backfd[1], STDOUT_FILENO) == -1)
result = -1;
}
}
/* close unneeded file descriptors */
close (frontfd[0]);
close (frontfd[1]);
close (backfd[0]);
close (backfd[1]);
return result;
}