tizen 2.4 release
[framework/web/wrt-commons.git] / modules / 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 #include<dpl/log/wrt_log.h>
25
26 namespace DPL {
27
28 ProcessPipe::ProcessPipe(PipeErrorPolicy err) : m_file(NULL), m_errPolicy(err)
29 {
30 }
31
32 ProcessPipe::~ProcessPipe()
33 {
34 }
35
36 void ProcessPipe::Open(const std::string & command)
37 {
38     if(m_file != NULL)
39     {
40         ThrowMsg(Exception::DoubleOpen, "Trying to open pipe second time. Close it first");
41     }
42
43     std::string stdErrRedirection;
44     switch(m_errPolicy)
45     {
46         case PipeErrorPolicy::NONE:                                      break;
47         case PipeErrorPolicy::OFF:   stdErrRedirection = " 2>/dev/null"; break;
48         case PipeErrorPolicy::PIPE:  stdErrRedirection = " 2>&1";        break;
49         default:                                                         break;
50     }
51
52     std::string fcommand = command + stdErrRedirection;
53     FILE * file = popen(fcommand.c_str(), "r");
54
55     // Throw an exception if an error occurred
56     if (file == NULL) {
57         ThrowMsg(FileInput::Exception::OpenFailed, fcommand);
58     }
59
60     // Save new descriptor
61     m_file = file;
62     m_fd = fileno(m_file);
63
64     WrtLogD("Opened pipe: %s", fcommand.c_str());
65 }
66
67 void ProcessPipe::Close()
68 {
69     if (m_fd == -1) {
70         return;
71     }
72
73     if (pclose(m_file) == -1) {
74         Throw(FileInput::Exception::CloseFailed);
75     }
76
77     m_fd = -1;
78     m_file = NULL;
79
80     WrtLogD("Closed pipe");
81 }
82
83 }