3 * Copyright (c) 2012 Samsung Electronics Co., Ltd.
5 * Licensed under the Apache License, Version 2.0 (the License);
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
21 #include <sys/types.h>
24 #include "utility/sync_util.h"
27 #define EXPORT_API __attribute__ ((visibility("default")))
30 #ifndef SYNC_AGENT_LOG
32 #define LOG_TAG "AF_SYNC_UTIL"
35 EXPORT_API int sync_agent_daemonize(void)
41 /* 1. if already a daemon running, return */
43 _DEBUG_WARNING("daemon is already running");
48 /* 2. Fork off the parent process */
51 if (pid < 0) { // if error
52 _DEBUG_ERROR("fork() error");
56 /* If we got a good PID, then we can exit the parent process,
57 * so that PPID can be the one of init process(1).
59 if (pid > 0) { // if parent process
63 /* At this point we are executing as the child process */
65 /* 3. Change the file mode mask (022 : permission = 644) */
68 /* 4. Create a new SID for the child process,
69 * so that PGID can be the one of PID of child process.
73 _DEBUG_ERROR("setsid() error");
78 /* 5. Change the current working directory.
79 * This prevents the current directory from being locked; hence not being able to remove it.
81 if ((chdir("/")) < 0) {
82 _DEBUG_ERROR("chdir() error");
87 /* 6. Redirect standard files to /dev/null */
89 fp = freopen("/dev/null", "r", stdin);
91 _DEBUG_ERROR("freopen() error");
93 fp = freopen("/dev/null", "w", stdout);
95 _DEBUG_ERROR("freopen() error");
97 fp = freopen("/dev/null", "w", stderr);
99 _DEBUG_ERROR("freopen() error");