6e4fb746337eca8e80c6b8c0cb926d2118bf71c3
[platform/core/security/cert-svc.git] / vcore / src / dpl / test / src / process_pipe.cpp
1 /*
2  * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  *    Licensed under the Apache License, Version 2.0 (the "License");
5  *    you may not use this file except in compliance with the License.
6  *    You may obtain a copy of the License at
7  *
8  *        http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *    Unless required by applicable law or agreed to in writing, software
11  *    distributed under the License is distributed on an "AS IS" BASIS,
12  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *    See the License for the specific language governing permissions and
14  *    limitations under the License.
15  */
16 /*
17  * @file        process_pipe.cpp
18  * @author      Tomasz Iwanek (t.iwanek@samsung.com)
19  * @version     1.0
20  * @brief       This file is the implementation pipe from process
21  */
22
23 #include <dpl/test/process_pipe.h>
24
25 namespace VcoreDPL {
26
27 ProcessPipe::ProcessPipe(PipeErrorPolicy err) : m_file(NULL), m_errPolicy(err)
28 {
29 }
30
31 ProcessPipe::~ProcessPipe()
32 {
33 }
34
35 void ProcessPipe::Open(const std::string & command)
36 {
37     if(m_file != NULL)
38     {
39         ThrowMsg(Exception::DoubleOpen, "Trying to open pipe second time. Close it first");
40     }
41
42     std::string stdErrRedirection;
43     switch(m_errPolicy)
44     {
45         case PipeErrorPolicy::NONE:                                      break;
46         case PipeErrorPolicy::OFF:   stdErrRedirection = " 2>/dev/null"; break;
47         case PipeErrorPolicy::PIPE:  stdErrRedirection = " 2>&1";        break;
48         default:                                                         break;
49     }
50
51     std::string fcommand = command + stdErrRedirection;
52     FILE * file = popen(fcommand.c_str(), "r");
53
54     // Throw an exception if an error occurred
55     if (file == NULL) {
56         ThrowMsg(FileInput::Exception::OpenFailed, fcommand);
57     }
58
59     // Save new descriptor
60     m_file = file;
61     m_fd = fileno(m_file);
62 }
63
64 void ProcessPipe::Close()
65 {
66     if (m_fd == -1) {
67         return;
68     }
69
70     if (pclose(m_file) == -1) {
71         Throw(FileInput::Exception::CloseFailed);
72     }
73
74     m_fd = -1;
75     m_file = NULL;
76 }
77
78 }