void cleanup(struct connection *pConn) { cleanupBuffers(pConn); if(pConn->hairtunes != NULL) { closePipe(&(pConn->hairtunes->in[0])); closePipe(&(pConn->hairtunes->in[1])); closePipe(&(pConn->hairtunes->out[0])); closePipe(&(pConn->hairtunes->out[1])); } if(pConn->keys != NULL) { if(pConn->keys->aesiv != NULL) { free(pConn->keys->aesiv); } if(pConn->keys->aeskey != NULL) { free(pConn->keys->aeskey); } if(pConn->keys->fmt != NULL) { free(pConn->keys->fmt); } pConn->keys = NULL; } if(pConn->clientSocket != -1) { close(pConn->clientSocket); pConn->clientSocket = -1; } }
void npclose(FILE *fp) { #if SYS_MSDOS if (myWrtr != 0 && myPipe == 0) writePipe(myCmds); #endif closePipe(&myRead); closePipe(&myWrtr); closePipe(&myPipe); deleteTemp(); }
char const *TcallDep::realise(char const *target, char const *targetMatch, Tstr *list, int maxIdx) { static TstrBuf rtn = ""; char const *comm = Tdep::realise(target, targetMatch, list, maxIdx); FILE *input = NULL; unsigned long rtnPos = 0; // if (NULL != (input = popen(comm, "r"))) if (NULL != (input = readPipe(comm))) { int ch; while (EOF != (ch = fgetc(input))) { if (isspace(ch)) { rtn[rtnPos++] = ' '; while (isspace(ch)) ch = fgetc(input); } if (EOF != ch) rtn[rtnPos++] = ch; } // pclose(input); closePipe(input); } rtn[rtnPos++] = '\0'; return ((char const*)rtn); }
PIPE_PTR connectToPipe(const char *name) { PIPE_PTR retval = INVALID_PIPE; struct sockaddr_un server; /* generate the server address */ server.sun_family = PF_UNIX; socketName(name, server.sun_path, sizeof(server.sun_path)); /* connect to the server */ retval = socket(PF_UNIX, SOCK_STREAM, 0); if (retval != INVALID_PIPE) { if (connect(retval, (struct sockaddr *)&server, sizeof(struct sockaddr_un)) == -1) { #if DEBUG printf("CLOSE %d %s(%d)\n", retval, __FILE__, __LINE__); #endif closePipe(retval); retval = INVALID_PIPE; } } return retval; }
void Pipe::connectToPipe(const std::string &pipeName) { //Console::log("Connecting to " + pipeName); closePipe(); bool done = false; while(!done) { m_handle = CreateFileA( pipeName.c_str(), // pipe name GENERIC_READ | // read and write access GENERIC_WRITE, 0, // no sharing nullptr, // default security attributes OPEN_EXISTING, // opens existing pipe 0, // default attributes nullptr); // no template file if(m_handle != INVALID_HANDLE_VALUE) { done = true; } Sleep(100); } //cout << "Connected" << endl; //DWORD mode = PIPE_READMODE_MESSAGE; DWORD mode = PIPE_READMODE_BYTE; BOOL success = SetNamedPipeHandleState( m_handle, // pipe handle &mode, // new pipe mode nullptr, // don't set maximum bytes nullptr); // don't set maximum time MLIB_ASSERT_STR(success != FALSE, "SetNamedPipeHandleState failed in Pipe::ConnectToPipe"); }
int ExecPipe::killProcess() { //! issue a forceful removal of the process kill(mProcess, SIGKILL); //! now clean up the process -- // wait needs to be called to remove the // zombie process. return closePipe(); }
int main(void) { PIPE * pipe = NULL; int ret; pid_t pid; ret = createPipe(&pipe); if (ret == -1) { printf("create fail!\n"); return -1; } pid = fork(); if (pid == 0) { setRDWRflag(pipe, WRITE); ret = writePipe(pipe, "Hello world!\n", 13); if (ret == -1) { printf("write pipe fail!\n"); closePipe(pipe); exit(1); } closePipe(pipe); exit(0); } if (pid > 0) { wait(NULL); setRDWRflag(pipe, READ); char buf[32]; bzero(buf, 32); ret = readPipe(pipe, buf, 13); if (ret == -1) { printf("read pipe fail!\n"); closePipe(pipe); exit(1); } printf("%s", buf); closePipe(pipe); exit(0); } }
Client::~Client(void) { closePipe(); // some language bar buttons are not unregistered properly if (!buttons_.empty()) { for (auto& item: buttons_) { textService_->removeButton(item.second); } } LangBarButton::clearIconCache(); }
// Close the socketpair bool GnashPluginScriptObject::closePipe() { // log_debug(__FUNCTION__); bool ret = closePipe(_sockfds[READFD]); if (ret) { ret = closePipe(_sockfds[WRITEFD]); } else { return false; } GError *error; GIOStatus rstatus = g_io_channel_shutdown(_iochan[READFD], true, &error); GIOStatus wstatus = g_io_channel_shutdown(_iochan[WRITEFD], true, &error); if ((rstatus == G_IO_STATUS_NORMAL) && (wstatus == G_IO_STATUS_NORMAL)) { return true; } else { return false; } return false; }
// send the request to the server // a sequence number will be added to the req object automatically. bool Client::sendRequest(Json::Value& req, Json::Value & result) { bool success = false; unsigned int seqNum = newSeqNum_++; req["seqNum"] = seqNum; // add a sequence number for the request std::string ret; DWORD rlen = 0; Json::FastWriter writer; std::string reqStr = writer.write(req); // convert the json object to string if (!connectingServerPipe_) { // if we're not in the middle of initializing the pipe connection // ensure that we're connected if (!connectServerPipe()) { // connection failed, schedule a timer to try again every 0.5 seconds if (connectServerTimerId_ != 0) { // do not create a new timer if there is an existing one. connectServerTimerId_ = SetTimer(NULL, 0, 500, [](HWND hwnd, UINT msg, UINT_PTR timerId, DWORD time) { auto client = timerIdToClients_[timerId]; if (client->connectServerPipe()) { // successfully connected, cancel the timer KillTimer(NULL, timerId); timerIdToClients_.erase(timerId); client->connectServerTimerId_ = 0; } }); timerIdToClients_[connectServerTimerId_] = this; } return false; } } if (sendRequestText(pipe_, reqStr.c_str(), reqStr.length(), ret)) { Json::Reader reader; success = reader.parse(ret, result); if (success) { if (result["seqNum"].asUInt() != seqNum) // sequence number mismatch success = false; } } else { // fail to send the request to the server if (connectingServerPipe_) { // we're in the middle of initializing the pipe connection return false; } else { closePipe(); // close the pipe connection since it's broken } } return success; }
bool mod_pipe::createServer() { bool reussite = false; if(!hPipe || hPipe == INVALID_HANDLE_VALUE) { hPipe = CreateNamedPipe(pipePath.c_str(), PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, 1, 0, 0, 30000, NULL); if (hPipe && hPipe != INVALID_HANDLE_VALUE) { reussite = ConnectNamedPipe(hPipe, NULL) ? TRUE : (GetLastError() == ERROR_PIPE_CONNECTED); } else { closePipe(); } } return reussite; }
BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: // Create a pipe to send data openPipe(); break; case DLL_PROCESS_DETACH: closePipe(); break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: break; } return TRUE; }
bool mod_pipe::createClient() { bool reussite = false; if(!hPipe || hPipe == INVALID_HANDLE_VALUE) { if (WaitNamedPipe(pipePath.c_str(), NMPWAIT_USE_DEFAULT_WAIT)) { hPipe = CreateFile(pipePath.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (hPipe != INVALID_HANDLE_VALUE) { DWORD dwMode = PIPE_READMODE_MESSAGE | PIPE_WAIT; if (!(reussite = SetNamedPipeHandleState(hPipe, &dwMode, NULL, NULL) != 0)) { closePipe(); } } } } return reussite; }
int __pclose(int fd) { idStream *is = getStreamData(getpid(), fd); if(!is) return -1; return closePipe(is->fd); }
deBool deProcess_start (deProcess* process, const char* commandLine, const char* workingDirectory) { pid_t pid = 0; int pipeIn[2] = { -1, -1 }; int pipeOut[2] = { -1, -1 }; int pipeErr[2] = { -1, -1 }; int statusPipe[2] = { -1, -1 }; if (process->state == PROCESSSTATE_RUNNING) { deProcess_setError(process, "Process already running"); return DE_FALSE; } else if (process->state == PROCESSSTATE_FINISHED) { deProcess_cleanupHandles(process); process->state = PROCESSSTATE_NOT_STARTED; } if (pipe(pipeIn) < 0 || pipe(pipeOut) < 0 || pipe(pipeErr) < 0 || pipe(statusPipe) < 0) { deProcess_setErrorFromErrno(process, "pipe() failed"); closePipe(pipeIn); closePipe(pipeOut); closePipe(pipeErr); closePipe(statusPipe); return DE_FALSE; } pid = fork(); if (pid < 0) { deProcess_setErrorFromErrno(process, "fork() failed"); closePipe(pipeIn); closePipe(pipeOut); closePipe(pipeErr); closePipe(statusPipe); return DE_FALSE; } if (pid == 0) { /* Child process. */ /* Close unused endpoints. */ close(pipeIn[1]); close(pipeOut[0]); close(pipeErr[0]); close(statusPipe[0]); /* Set status pipe to close on exec(). That way parent will know that exec() succeeded. */ if (fcntl(statusPipe[1], F_SETFD, FD_CLOEXEC) != 0) dieLastError(statusPipe[1], "Failed to set FD_CLOEXEC"); /* Map stdin. */ if (pipeIn[0] != STDIN_FILENO && dup2(pipeIn[0], STDIN_FILENO) != STDIN_FILENO) dieLastError(statusPipe[1], "dup2() failed"); close(pipeIn[0]); /* Stdout. */ if (pipeOut[1] != STDOUT_FILENO && dup2(pipeOut[1], STDOUT_FILENO) != STDOUT_FILENO) dieLastError(statusPipe[1], "dup2() failed"); close(pipeOut[1]); /* Stderr. */ if (pipeErr[1] != STDERR_FILENO && dup2(pipeErr[1], STDERR_FILENO) != STDERR_FILENO) dieLastError(statusPipe[1], "dup2() failed"); close(pipeErr[1]); /* Doesn't return. */ execProcess(commandLine, workingDirectory, statusPipe[1]); } else { /* Parent process. */ /* Check status. */ { char errBuf[256]; int result = 0; close(statusPipe[1]); while ((result = read(statusPipe[0], errBuf, 1)) == -1) if (errno != EAGAIN && errno != EINTR) break; if (result > 0) { /* Read full error msg. */ int errPos = 1; while (errPos < DE_LENGTH_OF_ARRAY(errBuf)) { result = read(statusPipe[0], errBuf+errPos, 1); if (result == -1) break; /* Done. */ errPos += 1; } /* Make sure str is null-terminated. */ errBuf[errPos] = 0; /* Close handles. */ close(statusPipe[0]); closePipe(pipeIn); closePipe(pipeOut); closePipe(pipeErr); /* Run waitpid to clean up zombie. */ waitpid(pid, &result, 0); deProcess_setError(process, errBuf); return DE_FALSE; } /* Status pipe is not needed. */ close(statusPipe[0]); } /* Set running state. */ process->pid = pid; process->state = PROCESSSTATE_RUNNING; /* Stdin, stdout. */ close(pipeIn[0]); close(pipeOut[1]); close(pipeErr[1]); process->standardIn = deFile_createFromHandle(pipeIn[1]); process->standardOut = deFile_createFromHandle(pipeOut[0]); process->standardErr = deFile_createFromHandle(pipeErr[0]); if (!process->standardIn) close(pipeIn[1]); if (!process->standardOut) close(pipeOut[0]); if (!process->standardErr) close(pipeErr[0]); } return DE_TRUE; }
/* * Class: VM_0005fProcess * Method: exec4 * Signature: (Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)I */ JNIEXPORT jint JNICALL Java_com_ibm_JikesRVM_VM_1Process_exec4 (JNIEnv *env, jobject self, jstring programName, jobjectArray argvArguments, jobjectArray environment, jstring dirPathStr) { // Get the program name StringPtr programString(convertString(env, programName)); #ifdef DEBUG fprintf(stderr, "program name is %s\n", programString.get()); #endif // Build argv array jsize argvLen = env->GetArrayLength((jarray) argvArguments); StringArray argv(argvLen); for (int i = 0; i < argvLen; ++i) { jstring arg = (jstring) env->GetObjectArrayElement(argvArguments, i); assert(arg); char *str = convertString(env, arg); #ifdef DEBUG fprintf(stderr, "arg %d is %s\n", i, str); #endif argv.setAndAdoptString(i, str); } // Build environment array (if any) jsize envpLen = (environment != 0) ? env->GetArrayLength((jarray) environment) : 0; StringArray envp(envpLen); for (int i = 0; i < envpLen; ++i) { jstring arg = (jstring) env->GetObjectArrayElement(environment, i); assert(arg); char *str = convertString(env, arg); #ifdef DEBUG fprintf(stderr, "env %d is %s\n", i, str); #endif envp.setAndAdoptString(i, str); } // Get the directory path (if any) StringPtr dirPath( (dirPathStr != 0) ? convertString(env, dirPathStr) : 0 ); #ifdef DEBUG fprintf(stderr, "working directory is %s\n", (dirPath.get() != 0) ? dirPath.get() : "unspecified, will use current"); #endif // Create pipes to communicate with child process. jclass ProcessClassID = env->FindClass( "com/ibm/JikesRVM/VM_Process" ); assert(ProcessClassID); int inputPipe[2], outputPipe[2], errorPipe[2]; pid_t fid = -1; int ret = createPipe(inputPipe, env, ProcessClassID, self, "inputDescriptor", OUTPUT); if (ret) goto fail; ret = createPipe(outputPipe, env, ProcessClassID, self, "outputDescriptor", INPUT); if (ret) goto close_inputPipe_and_fail; ret = createPipe(errorPipe, env, ProcessClassID, self, "errorDescriptor", INPUT); if (ret) goto close_outputPipe_and_fail; // do the exec fid = fork(); if (fid == 0) { // child // If a working directory was specified, try to // make it the current directory. if (dirPath.get() != 0) { if (chdir(dirPath.get()) != 0) { #ifdef DEBUG fprintf(stderr, "chdir() failed: %s\n", strerror(errno)); #endif // FIXME: // Presumably we should throw some sort of I/O error // (from Runtime.exec()) if we can't change into the // working directory the caller specified. // Instead, we just return this value as the exit code. exit(EXIT_STATUS_BAD_WORKING_DIR); } } #define SHOULD_NEVER_FAIL(cmd) do \ { \ if ((cmd) < 0) { \ perror(#cmd " failed, but should never; aborting"); \ abort(); \ } \ } while(0) /* Attach pipes to stdin, stdout, stderr These absolutely should never fail. */ SHOULD_NEVER_FAIL(dup2(inputPipe[INPUT], 0)); SHOULD_NEVER_FAIL(dup2(outputPipe[OUTPUT], 1)); SHOULD_NEVER_FAIL(dup2(errorPipe[OUTPUT], 2)); /* Close the original file descriptors returned by pipe(). Since they're already open, they should never fail either. */ SHOULD_NEVER_FAIL(closePipe(inputPipe)); SHOULD_NEVER_FAIL(closePipe(outputPipe)); SHOULD_NEVER_FAIL(closePipe(errorPipe)); // Set environment for child process. if (environment != 0) { environ = envp.get(); } #if 0 else { fprintf(stderr, "Current environment:\n"); char **p = environ; while (*p != 0 ) { fprintf(stderr, "\t%s\n", *p); ++p; } } #endif // Execute the program. // XXX See comment below on error handling. // int err = execvp(programString.get(), argv.get()); (void) execvp(programString.get(), argv.get()); // We get here only if an error occurred. #ifdef DEBUG fprintf(stderr, "execvp() failed: %s\n", strerror(errno)); #endif programString.release(); argv.release(); envp.release(); dirPath.release(); // FIXME: // Unfortunately, it's difficult to convey an error code // back to the parent process to let it know that we couldn't // actually execute the program. We could use shared memory // or a special pipe to send the error information. // For now, just exit with a non-zero status. /* However, traditionally the shell and xargs use status 127 to mean that * they were unable to find something to execute. * To quote the bash manpage, "If a command is found * but is not executable, the return status is 126.¨ * We shall adopt those customs here. --Steve Augart*/ if (errno == ENOENT || errno == ENOTDIR) exit(EXIT_STATUS_EXECUTABLE_NOT_FOUND); exit(EXIT_STATUS_COULD_NOT_EXECUTE); // couldn't be executed for some // other reason. } else if (fid > 0) { // parent // Store child's pid jfieldID pidFieldID = env->GetFieldID(ProcessClassID, "pid", "I"); assert(pidFieldID); env->SetIntField(self, pidFieldID, fid); #ifdef DEBUG fprintf(stderr, "child process id is %d\n", fid); #endif // Close unused ends of pipes // input side of child's stdin: SHOULD_NEVER_FAIL(close(inputPipe[INPUT])); // output side of child's stdout: SHOULD_NEVER_FAIL(close(outputPipe[OUTPUT])); // output side of child's stderr SHOULD_NEVER_FAIL(close(errorPipe[OUTPUT])); // Note: memory for programName, argv, and envp will be cleaned // up automatically #ifdef DEBUG fprintf(stderr, "done exec\n"); #endif return fid; } else { // An error occurred in fork() #ifdef DEBUG fprintf(stderr, "fork() failed: %s\n", strerror(errno)); #endif // Close pipes closePipe(errorPipe); close_outputPipe_and_fail: closePipe(outputPipe); close_inputPipe_and_fail: closePipe(inputPipe); fail: return -1; } }
void run(char ** args){ bool runBg = false; clock_t start, end; pid_t pid; double elapsed; int i=0; while(args[i] != NULL){ i++; printf("%i\n", i); } if (strcmp(&(args[i-1][strlen(args[i-1])-1]), "&") == 0) runBg = true; else runBg =false; if(runBg) printf("%s\n", "bg is runnign"); if (runBg){ if(pipe(p1)== -1) perror("Pipe creation error"); } //Starting the timer start = clock(); //printf("%s\n", start); /*Create pipe to execute command line actions and arguments*/ pid = startFork(); if(0 == pid){ if (runBg){ if (dup2(p1[STDIN_FILENO],STDIN_FILENO)== -1) errHandler("dup2 error"); closePipe(p1); } if (execvp(args[0], args) < 0) errHandler("That is not a valid command.."); } if (runBg){ closePipe(p1); } else{ waitpid(pid, NULL, 0); end = clock(); elapsed = ((double) (end-start)) / CLOCKS_PER_SEC; fprintf(stderr, "Time elapsed for process: %f s\n", elapsed); printf("%i\n", pid); } }
void Pipe::createPipe(const std::string &pipeName, bool block) { //Console::log() << "creating pipe " << pipeName << std::endl; closePipe(); const UINT PipeBufferSize = 100000; DWORD dwRes; PSID pEveryoneSID = nullptr, pAdminSID = nullptr; PACL pACL = nullptr; PSECURITY_DESCRIPTOR pSD = nullptr; EXPLICIT_ACCESS ea[1]; SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_WORLD_SID_AUTHORITY; SID_IDENTIFIER_AUTHORITY SIDAuthNT = SECURITY_NT_AUTHORITY; SECURITY_ATTRIBUTES attributes; HKEY hkSub = nullptr; // Create a well-known SID for the Everyone group. BOOL success = AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &pEveryoneSID); MLIB_ASSERT_STR(success != FALSE, "AllocateAndInitializeSid failed in Pipe::CreatePipe"); // Initialize an EXPLICIT_ACCESS structure for an ACE. // The ACE will allow Everyone read access to the key. ZeroMemory(&ea, sizeof(EXPLICIT_ACCESS)); ea[0].grfAccessPermissions = FILE_ALL_ACCESS; ea[0].grfAccessMode = SET_ACCESS; ea[0].grfInheritance= NO_INHERITANCE; ea[0].Trustee.TrusteeForm = TRUSTEE_IS_SID; ea[0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP; ea[0].Trustee.ptstrName = (LPTSTR) pEveryoneSID; // Create a new ACL that contains the new ACEs. dwRes = SetEntriesInAcl(1, ea, nullptr, &pACL); MLIB_ASSERT_STR(dwRes == ERROR_SUCCESS, "SetEntriesInAcl failed in Pipe::CreatePipe"); // Initialize a security descriptor. pSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH); MLIB_ASSERT_STR(pSD != nullptr, "LocalAlloc failed in Pipe::CreatePipe"); success = InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION); MLIB_ASSERT_STR(success != FALSE, "InitializeSecurityDescriptor failed in Pipe::CreatePipe"); // Add the ACL to the security descriptor. success = SetSecurityDescriptorDacl(pSD, TRUE, // bDaclPresent flag pACL, FALSE); MLIB_ASSERT_STR(success != FALSE, "SetSecurityDescriptorDacl failed in Pipe::CreatePipe"); // Initialize a security attributes structure. attributes.nLength = sizeof(SECURITY_ATTRIBUTES); attributes.lpSecurityDescriptor = pSD; attributes.bInheritHandle = FALSE; std::string fullPipeName = std::string("\\\\.\\pipe\\") + pipeName; m_handle = CreateNamedPipeA( fullPipeName.c_str(), // pipe name PIPE_ACCESS_DUPLEX, // read/write access PIPE_TYPE_MESSAGE | // message type pipe PIPE_READMODE_MESSAGE | // message-read mode PIPE_WAIT, // blocking mode PIPE_UNLIMITED_INSTANCES, // max. instances PipeBufferSize, // output buffer size PipeBufferSize, // input buffer size NMPWAIT_USE_DEFAULT_WAIT, // client time-out &attributes); // default security attribute MLIB_ASSERT_STR(m_handle != INVALID_HANDLE_VALUE, "CreateNamedPipe failed in Pipe::CreatePipe"); // // Block until a connection comes in // if(block) { Console::log("Pipe created, waiting for connection"); BOOL Connected = (ConnectNamedPipe(m_handle, nullptr) != 0); MLIB_ASSERT_STR(Connected != FALSE, "ConnectNamedPipe failed in Pipe::CreatePipe"); Console::log("Connected"); } else { //cout << "Not blocking for connection to complete" << endl; } }
mod_pipe::~mod_pipe(void) { closePipe(); }
// dwCreationDisposition can be one of the following values from CreateFile: // CREATE_NEW Fail if the pipe already exists // OPEN_EXISTING Fail if the pipe does not exist Pipe* createPipe(const TCHAR* name, DWORD dwCreationDisposition) { if (dwCreationDisposition != CREATE_NEW && dwCreationDisposition != OPEN_EXISTING) return NULL; BOOL result = FALSE; Pipe* pipe = new Pipe; if (pipe == NULL) return NULL; pipe->hReadableEvent = NULL; pipe->hWriteableEvent = NULL; pipe->hMutex = NULL; pipe->hFileMapping = NULL; pipe->pBuffer = NULL; pipe->bufferLength = 16384; TCHAR mutexName[100]; _stprintf(mutexName, TEXT("%s.mutex"), name); pipe->hMutex = CreateMutex(NULL, FALSE, mutexName); if (pipe->hMutex == NULL) goto cleanup; else if (GetLastError() == ERROR_ALREADY_EXISTS) { if (dwCreationDisposition == CREATE_NEW) goto cleanup; } else { if (dwCreationDisposition == OPEN_EXISTING) goto cleanup; } TCHAR readableEventName[100]; _stprintf(readableEventName, TEXT("%s.readable"), name); pipe->hReadableEvent = CreateEvent(NULL, TRUE, FALSE, readableEventName); if (pipe->hReadableEvent == NULL) goto cleanup; else if (GetLastError() == ERROR_ALREADY_EXISTS) { if (dwCreationDisposition == CREATE_NEW) goto cleanup; } else { if (dwCreationDisposition == OPEN_EXISTING) goto cleanup; } TCHAR writeableEventName[100]; _stprintf(writeableEventName, TEXT("%s.writeable"), name); pipe->hWriteableEvent = CreateEvent(NULL, TRUE, TRUE, writeableEventName); if (pipe->hWriteableEvent == NULL) goto cleanup; else if (GetLastError() == ERROR_ALREADY_EXISTS) { if (dwCreationDisposition == CREATE_NEW) goto cleanup; } else { if (dwCreationDisposition == OPEN_EXISTING) goto cleanup; } TCHAR memName[100]; _stprintf(memName, TEXT("%s.mem"), name); pipe->hFileMapping = CreateFileMapping((HANDLE)INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, pipe->bufferLength, memName); if (pipe->hFileMapping == NULL) goto cleanup; else if (GetLastError() == ERROR_ALREADY_EXISTS) { if (dwCreationDisposition == CREATE_NEW) goto cleanup; } else { if (dwCreationDisposition == OPEN_EXISTING) goto cleanup; } pipe->pBuffer = (char*)MapViewOfFile(pipe->hFileMapping, FILE_MAP_WRITE, 0, 0, 0); if (pipe->pBuffer == NULL) goto cleanup; memset(pipe->pBuffer, 0, pipe->bufferLength); result = TRUE; cleanup: if (result == FALSE) { closePipe(pipe); pipe = NULL; } return pipe; }
/** * \brief Reopen pipe to read again */ void PipeListener::reopenPipe() { closePipe(); openPipe(); }
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * * NAME : ~NamedPipe * * PURPOSE : Destructor * *-----------------------------------------------------------------------------*/ NamedPipe::~NamedPipe() { closePipe(); //unlink(fifo_path); // Do not remove! maybe a process is still reading from this pipe. }
void Process::internalExec(const String programName, const List<String>& args, const List<String>& env, bool mergeOutput) { HANDLE hInputRead = INVALID_HANDLE_VALUE; HANDLE hInputWrite = INVALID_HANDLE_VALUE; HANDLE hOutputRead = INVALID_HANDLE_VALUE; HANDLE hOutputWrite = INVALID_HANDLE_VALUE; HANDLE hErrorRead = INVALID_HANDLE_VALUE; HANDLE hErrorWrite = INVALID_HANDLE_VALUE; SECURITY_ATTRIBUTES sa; DWORD errorNumber; if (m_hasStarted) { throw SystemException("Failed to create process: Cannot start two " "processes with one Process object"); } // Set up the security attributes struct. sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.lpSecurityDescriptor = NULL; sa.bInheritHandle = TRUE; // Create the child input pipe. if (!::CreatePipe(&hInputRead, &hInputWrite, &sa, 0)) { throw SystemException(String("Failed to create process. Couldn't create " "pipe: ") + WinUtil::getLastErrorMessage()); } // Prevent the stdin write handle from being inherited if (!::SetHandleInformation(hInputWrite, HANDLE_FLAG_INHERIT, 0)) { errorNumber = ::GetLastError(); closePipe(hInputRead, hInputWrite); throw SystemException(String("Failed to create process. Couldn't set " "handle inheritance: ") + WinUtil::getErrorMessage(errorNumber)); } // Create the child output pipe. if (!::CreatePipe(&hOutputRead, &hOutputWrite, &sa, 0)) { errorNumber = GetLastError(); closePipe(hInputRead, hInputWrite); throw SystemException(String("Failed to create process. Couldn't create " "pipe: ") + WinUtil::getErrorMessage(errorNumber)); } // Prevent the stdout read handle from being inherited if (!::SetHandleInformation(hOutputRead, HANDLE_FLAG_INHERIT, 0)) { errorNumber = ::GetLastError(); closePipe(hInputRead, hInputWrite); closePipe(hOutputRead, hOutputWrite); throw SystemException(String("Failed to create process. Couldn't " "set handle inheritance: ") + WinUtil::getErrorMessage(errorNumber)); } if (!mergeOutput) { // Create the child error pipe. if (!::CreatePipe(&hErrorRead, &hErrorWrite, &sa, 0)) { errorNumber = ::GetLastError(); closePipe(hInputRead, hInputWrite); closePipe(hOutputRead, hOutputWrite); throw SystemException(String("Failed to create process. Couldn't " "create pipe: ") + WinUtil::getErrorMessage(errorNumber)); } // Prevent the stderr read handle from being inherited if (!::SetHandleInformation(hErrorRead, HANDLE_FLAG_INHERIT, 0)) { errorNumber = ::GetLastError(); closePipe(hInputRead, hInputWrite); closePipe(hOutputRead, hOutputWrite); closePipe(hErrorRead, hErrorWrite); throw SystemException(String("Failed to create process. Couldn't " "set handle inheritance: ") + WinUtil::getErrorMessage(errorNumber)); } } else { // If we are merging the output, just duplicate the stdout write // handle and make the child use it as its stderr if (!::DuplicateHandle(::GetCurrentProcess(), // Source Process hOutputWrite, // Source HANDLE ::GetCurrentProcess(), // Destination Process &hErrorWrite, // Destination HANDLE address 0, // Access rights (ignored due to DUPLICATE_SAME_ACCESS) TRUE, // Make the HANDLE inheritable DUPLICATE_SAME_ACCESS)) // Use same access rights { closePipe(hInputRead, hInputWrite); closePipe(hOutputRead, hOutputWrite); throw SystemException(String("Failed to create process. Couldn't " "duplicate handle: ") + WinUtil::getLastErrorMessage()); } } // Start the process m_processHandle = launchProcess(programName, args, env, hInputRead, hOutputWrite, hErrorWrite); // Close our copies of the pipe handles that the child process will use. ::CloseHandle(hInputRead); ::CloseHandle(hOutputWrite); ::CloseHandle(hErrorWrite); // Make stream objects m_stdin = new FileOutputStream(hInputWrite); m_stdout = new FileInputStream(hOutputRead); if (!mergeOutput) { m_stderr = new FileInputStream(hErrorRead); } m_hasStarted = true; }
void spawn_job(job_t *j, bool fg) { pid_t pid; process_t *p; int countProcess = 0; int loopCounter = -1; int i; //count number of processes in the job for(p = j->first_process; p; p = p->next) { countProcess++; } //printf("count process: %d \n", countProcess); int pipefd[countProcess-1][2]; //initialize 2-dimensional array [number of process][input/output] //printf("test"); //open all pipes if(countProcess > 1) { for(i = 0; i < (countProcess-1); i++) { //printf("piped %d \n", i); pipe(pipefd[i]); } } for(p = j->first_process; p; p = p->next) { /* YOUR CODE HERE? */ /* Builtin commands are already taken care earlier */ loopCounter++; switch (pid = fork()) { // int status; case -1: /* fork failure */ perror("fork"); exit(EXIT_FAILURE); case 0: /* child process */ p->pid = getpid(); new_child(j, p, fg); /* YOUR CODE HERE? Child-side code for new process. */ if (p->ifile != NULL) { int fd = open(p->ifile, O_RDONLY); dup2(fd, STDIN_FILENO); } if (p->ofile != NULL) { int fd = open(p->ofile, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); dup2(fd, STDOUT_FILENO); } //pipe if(countProcess > 1) { //printf("begin piping \n"); //first process is output //need to loop through number of process and close all pipes if(p == j->first_process) { dup2(pipefd[loopCounter][1], 1); //duplicate output as output for next process closePipe(pipefd, countProcess); } //last process else if (p->next == NULL) { dup2(pipefd[loopCounter-1][0], 0); closePipe(pipefd, countProcess); } //for middle: dup both input and output else { dup2(pipefd[loopCounter][1], 1); dup2(pipefd[loopCounter-1][0], 0); closePipe(pipefd, countProcess); } } printf("%d (Launched): %s\n", j->pgid, j->commandinfo); execvp(p->argv[0], p->argv); perror("New child should have done an exec"); exit(EXIT_FAILURE); /* NOT REACHED */ break; /* NOT REACHED */ default: /* parent */ /* establish child process group */ p->pid = pid; set_child_pgid(j, p); /* YOUR CODE HERE? Parent-side code for new process. */ if (p->next == NULL) //if last process { process_t *p2; p2 = j->first_process; while(p2 != NULL) { //printf("waiting for process \n"); //if fg true waiting, else bg stuff if(fg == true) { waiting(p2); } else { struct sigaction action; action.sa_sigaction = sighandler; sigfillset(&action.sa_mask); action.sa_flags = SA_SIGINFO; sigaction(SIGCHLD, &action, NULL); } closePipe(pipefd, countProcess); p2 = p2->next; } } //wait for child to finish } /* YOUR CODE HERE? Parent-side code for new job.*/ //printf("assign terminal back to dsh\n"); seize_tty(getpid()); // assign the terminal back to dsh } }
//parseMessage(tConn->recv.data, tConn->recv.mark, &tConn->resp, ipstr, pHWADDR, tConn->keys); int parseMessage(struct connection *pConn, unsigned char *pIpBin, unsigned int pIpBinLen, char *pHWID) { int tReturn = 0; // 0 = good, 1 = Needs More Data, -1 = close client socket. if(pConn->resp.data == NULL) { initBuffer(&(pConn->resp), MAX_SIZE); } char *tContent = getFromHeader(pConn->recv.data, "Content-Length", NULL); if(tContent != NULL) { int tContentSize = atoi(tContent); if(pConn->recv.marker == 0 || strlen(pConn->recv.data+pConn->recv.marker) != tContentSize) { if(isLogEnabledFor(HEADER_LOG_LEVEL)) { slog(HEADER_LOG_LEVEL, "Content-Length: %s value -> %d\n", tContent, tContentSize); if(pConn->recv.marker != 0) { slog(HEADER_LOG_LEVEL, "ContentPtr has %d, but needs %d\n", strlen(pConn->recv.data+pConn->recv.marker), tContentSize); } } // check if value in tContent > 2nd read from client. return 1; // means more content-length needed } } else { slog(LOG_DEBUG_VV, "No content, header only\n"); } // "Creates" a new Response Header for our response message addToShairBuffer(&(pConn->resp), "RTSP/1.0 200 OK\r\n"); if(isLogEnabledFor(LOG_INFO)) { int tLen = strchr(pConn->recv.data, ' ') - pConn->recv.data; if(tLen < 0 || tLen > 20) { tLen = 20; } slog(LOG_INFO, "********** RECV %.*s **********\n", tLen, pConn->recv.data); } if(pConn->password != NULL) { } if(buildAppleResponse(pConn, pIpBin, pIpBinLen, pHWID)) // need to free sig { slog(LOG_DEBUG_V, "Added AppleResponse to Apple-Challenge request\n"); } // Find option, then based on option, do different actions. if(strncmp(pConn->recv.data, "OPTIONS", 7) == 0) { propogateCSeq(pConn); addToShairBuffer(&(pConn->resp), "Public: ANNOUNCE, SETUP, RECORD, PAUSE, FLUSH, TEARDOWN, OPTIONS, GET_PARAMETER, SET_PARAMETER\r\n"); } else if(!strncmp(pConn->recv.data, "ANNOUNCE", 8)) { char *tContent = pConn->recv.data + pConn->recv.marker; int tSize = 0; char *tHeaderVal = getFromContent(tContent, "a=aesiv", &tSize); // Not allocated memory, just pointing if(tSize > 0) { int tKeySize = 0; char tEncodedAesIV[tSize + 2]; getTrimmed(tHeaderVal, tSize, TRUE, TRUE, tEncodedAesIV); slog(LOG_DEBUG_VV, "AESIV: [%.*s] Size: %d Strlen: %d\n", tSize, tEncodedAesIV, tSize, strlen(tEncodedAesIV)); char *tDecodedIV = decode_base64((unsigned char*) tEncodedAesIV, tSize, &tSize); // grab the key, copy it out of the receive buffer tHeaderVal = getFromContent(tContent, "a=rsaaeskey", &tKeySize); char tEncodedAesKey[tKeySize + 2]; // +1 for nl, +1 for \0 getTrimmed(tHeaderVal, tKeySize, TRUE, TRUE, tEncodedAesKey); slog(LOG_DEBUG_VV, "AES KEY: [%s] Size: %d Strlen: %d\n", tEncodedAesKey, tKeySize, strlen(tEncodedAesKey)); // remove base64 coding from key char *tDecodedAesKey = decode_base64((unsigned char*) tEncodedAesKey, tKeySize, &tKeySize); // Need to free DecodedAesKey // Grab the formats int tFmtpSize = 0; char *tFmtp = getFromContent(tContent, "a=fmtp", &tFmtpSize); // Don't need to free tFmtp = getTrimmedMalloc(tFmtp, tFmtpSize, TRUE, FALSE); // will need to free slog(LOG_DEBUG_VV, "Format: %s\n", tFmtp); RSA *rsa = loadKey(); // Decrypt the binary aes key char *tDecryptedKey = malloc(RSA_size(rsa) * sizeof(char)); // Need to Free Decrypted key //char tDecryptedKey[RSA_size(rsa)]; if(RSA_private_decrypt(tKeySize, (unsigned char *)tDecodedAesKey, (unsigned char*) tDecryptedKey, rsa, RSA_PKCS1_OAEP_PADDING) >= 0) { slog(LOG_DEBUG, "Decrypted AES key from RSA Successfully\n"); } else { slog(LOG_INFO, "Error Decrypting AES key from RSA\n"); } free(tDecodedAesKey); RSA_free(rsa); setKeys(pConn->keys, tDecodedIV, tDecryptedKey, tFmtp); propogateCSeq(pConn); } } else if(!strncmp(pConn->recv.data, "SETUP", 5)) { // Setup pipes // struct comms *tComms = pConn->hairtunes; // if (! (pipe(tComms->in) == 0 && pipe(tComms->out) == 0)) // { // slog(LOG_INFO, "Error setting up hairtunes communications...some things probably wont work very well.\n"); // } // Setup fork char tPort[8] = "6000"; // get this from dup()'d stdout of child pid printf("******** SETUP!!!!!\n"); #ifndef BOXEE int tPid = fork(); if(tPid == 0) { #endif int tDataport=0; char tCPortStr[8] = "59010"; char tTPortStr[8] = "59012"; int tSize = 0; char *tFound =getFromSetup(pConn->recv.data, "control_port", &tSize); getTrimmed(tFound, tSize, 1, 0, tCPortStr); tFound = getFromSetup(pConn->recv.data, "timing_port", &tSize); getTrimmed(tFound, tSize, 1, 0, tTPortStr); slog(LOG_DEBUG_VV, "converting %s and %s from str->int\n", tCPortStr, tTPortStr); int tControlport = atoi(tCPortStr); int tTimingport = atoi(tTPortStr); slog(LOG_DEBUG_V, "Got %d for CPort and %d for TPort\n", tControlport, tTimingport); char *tRtp = NULL; char *tPipe = NULL; char *tAoDriver = NULL; char *tAoDeviceName = NULL; char *tAoDeviceId = NULL; struct keyring *tKeys = pConn->keys; #ifndef BOXEE // ************************************************* // ** Setting up Pipes, AKA no more debug/output ** // ************************************************* dup2(tComms->in[0],0); // Input to child closePipe(&(tComms->in[0])); closePipe(&(tComms->in[1])); dup2(tComms->out[1], 1); // Output from child closePipe(&(tComms->out[1])); closePipe(&(tComms->out[0])); pConn->keys = NULL; pConn->hairtunes = NULL; // Free up any recv buffers, etc.. if(pConn->clientSocket != -1) { close(pConn->clientSocket); pConn->clientSocket = -1; } cleanupBuffers(pConn); #endif hairtunes_init(tKeys->aeskey, tKeys->aesiv, tKeys->fmt, tControlport, tTimingport, tDataport, tRtp, tPipe, tAoDriver, tAoDeviceName, tAoDeviceId); #ifndef BOXEE // Quit when finished. slog(LOG_DEBUG, "Returned from hairtunes init....returning -1, should close out this whole side of the fork\n"); return -1; } else if(tPid >0) { // Ensure Connection has access to the pipe. closePipe(&(tComms->in[0])); closePipe(&(tComms->out[1])); char tFromHairtunes[80]; int tRead = read(tComms->out[0], tFromHairtunes, 80); if(tRead <= 0) { slog(LOG_INFO, "Error reading port from hairtunes function, assuming default port: %d\n", tPort); } else { int tSize = 0; char *tPortStr = getFromHeader(tFromHairtunes, "port", &tSize); if(tPortStr != NULL) { getTrimmed(tPortStr, tSize, TRUE, FALSE, tPort); } else { slog(LOG_INFO, "Read %d bytes, Error translating %s into a port\n", tRead, tFromHairtunes); } } int tSize; #endif // READ Ports from here?close(pConn->hairtunes_pipes[0]); propogateCSeq(pConn); tSize = 0; char *tTransport = getFromHeader(pConn->recv.data, "Transport", &tSize); addToShairBuffer(&(pConn->resp), "Transport: "); addNToShairBuffer(&(pConn->resp), tTransport, tSize); // Append server port: addToShairBuffer(&(pConn->resp), ";server_port="); addToShairBuffer(&(pConn->resp), tPort); addToShairBuffer(&(pConn->resp), "\r\nSession: DEADBEEF\r\n"); #ifndef BOXEE } else { slog(LOG_INFO, "Error forking process....dere' be errors round here.\n"); return -1; } #endif } else if(!strncmp(pConn->recv.data, "TEARDOWN", 8)) { // Be smart? Do more finish up stuff... addToShairBuffer(&(pConn->resp), "Connection: close\r\n"); propogateCSeq(pConn); #ifndef BOXEE close(pConn->hairtunes->in[1]); slog(LOG_DEBUG, "Tearing down connection, closing pipes\n"); #else hairtunes_cleanup(); #endif //close(pConn->hairtunes->out[0]); tReturn = -1; // Close client socket, but sends an ACK/OK packet first } else if(!strncmp(pConn->recv.data, "FLUSH", 5)) { // TBD FLUSH #ifndef BOXEE write(pConn->hairtunes->in[1], "flush\n", 6); #else hairtunes_flush(); #endif propogateCSeq(pConn); } else if(!strncmp(pConn->recv.data, "SET_PARAMETER", 13)) { propogateCSeq(pConn); int tSize = 0; char *tVol = getFromHeader(pConn->recv.data, "volume", &tSize); slog(LOG_DEBUG_VV, "About to write [vol: %.*s] data to hairtunes\n", tSize, tVol); // TBD VOLUME #ifndef BOXEE write(pConn->hairtunes->in[1], "vol: ", 5); write(pConn->hairtunes->in[1], tVol, tSize); write(pConn->hairtunes->in[1], "\n", 1); #else hairtunes_setvolume(atof(tVol)); #endif slog(LOG_DEBUG_VV, "Finished writing data write data to hairtunes\n"); } else { slog(LOG_DEBUG, "\n\nUn-Handled recv: %s\n", pConn->recv.data); propogateCSeq(pConn); } addToShairBuffer(&(pConn->resp), "\r\n"); return tReturn; }
/* process input stored in line i.e. print line */ void processLine(/*const*/ char * line) { command = parser_parse(line); /* print length and content of line */ //printf("%zd - %s\n", strlen(line), line); // loop until there is no command left while(command != NULL) { switch(command->kind) // found the kinds in parser.h: enum cmd_kind {printf("\nswitch\n\n"); case EXIT: // check if user wants to quit quit = 1; printf("\nShell beendet.\n\n"); return; /*case JOB : break;*/ //Aufgabe Option Prozesssynchronisation case CD: // change directory if(chdir(command->cd.path) == -1) perror("no such directory"); else { if (getcwd(cwd, sizeof(cwd)) == NULL) perror("getcwd() error"); } break; case ENV : if(command->env.value != NULL) // set environment var { if((getenv(command->env.name)) != NULL) printf("Variable already exists\n"); else { setenv(command->env.name, command->env.value, 0); printf("Variable set.\n"); } } else if(command->env.name != NULL) // unset environment var { if((getenv(command->env.name)) != NULL) { unsetenv(command->env.name); printf("Variable unset.\n"); } else printf("Variable does not exist.\n"); } else printf("Bad arguments.\n"); break; case PROG : { pid_t child_pid = fork(); //Start in own process int error; if (child_pid == -1) //failure { perror("fork failed"); break; } if (child_pid == 0) // child process { if (!command->prog.background) // foreground program setup_signal_handler(SIGINT, SIG_DFL); //enable interrupt else freopen ("/dev/null", "w", stdout); //ignore output if (command->prog.input) // Input-File -> set as standard in freopen (command->prog.input, "r", stdin); if (command->prog.output) // Output-File -> set as standard out freopen (command->prog.output, "w", stdout); // there has to be Null in the end command->prog.argv[command->prog.argc] = NULL; // execute program error = execvpe(command->prog.argv[0], command->prog.argv, NULL); if(error!=-1) exit(123); //Couldn't execute perror("Couldn't find program"); exit(742); } else // parent process { // foreground process if (!command->prog.background) { // wait for child to finish int status = 0; if (waitpid(child_pid, &status, 0) == -1) perror("Child process not finish"); } } break; } case PIPE : { pid_t child1; //child1 pid_t child2; //child2 int fd[2]; pipe(fd); int status; char buffer[10000]; //parent read and child write!!!! prog_args* test = command->prog.next->next; if (test == NULL){ //only one pipe //printf("SINGLE\n"); if((child1=fork())<0){ perror("fork"); exit(-1); } if(child1==0){ dup2(fd[WRITE_END], 1); closePipe(fd); execvp(command->prog.argv[0], command->prog.argv); } child2 = fork(); if(child2==0) { dup2(fd[READ_END],0); closePipe(fd); execvp(command->prog.next->argv[0],command->prog.next->argv); } closePipe(fd); waitpid(child1,NULL,0); waitpid(child2,NULL,0); break; } else { //multiple pipes //printf("MULTIPIP\n"); int pcounter = 2; pid_t pids[30]; int i; //prog pointers prog_args* pnext = command->prog.next->next; //execute char** enext = pnext->argv; //char** enext = pnext->argv; //pipe int fd[2]; int fdd[2]; pipe(fdd); pipe(fd); if((pids[0]=fork())<0){ perror("fork"); break; } if(pids[0]==0){ dup2(fdd[WRITE_END], 1); closePipe(fdd); execvp(command->prog.argv[0], command->prog.argv); break; } if((pids[1]=fork())<0){ perror("fork"); } if(pids[1]==0){ dup2(fdd[READ_END],0); closePipe(fdd); dup2(fd[WRITE_END],1); closePipe(fd); execvp(command->prog.next->argv[0],command->prog.next->argv); break; } while(pnext != NULL){ if((pids[pcounter]=fork())<0){ perror("fork"); break; } if(pids[pcounter]==0){ if((pnext->next)==NULL){ dup2(fd[READ_END],0); //printf("InnerPipe\n"); closePipe(fd); closePipe(fdd); //printf("Enext:%s\n",enext[0]); int fu ; fu = execvp(enext[0],enext); break; } else { printf("GO ON \n"); break; } } //printf("PARENT\n"); closePipe(fdd); //closePipe(fd); //waitpid(pids[pcounter],NULL,0); pnext=pnext->next; pcounter++; break; } closePipe(fd); closePipe(fdd); for(i=0;i<=pcounter;i++){ //printf("Wait for PID%i\n",i); waitpid(pids[i],NULL,0); } break; } //Multipipes end break; } default: printf("Command not found\n"); } // get next command command = command->next; } parser_free(command); }
Pipe::~Pipe() { closePipe(); }