Skip to content

Commit 564d43e

Browse files
authored
Merge pull request #505 from ejohnstown/forking
Forking
2 parents 07f901d + 9c9cb5a commit 564d43e

1 file changed

Lines changed: 37 additions & 8 deletions

File tree

apps/wolfsshd/wolfsshd.c

Lines changed: 37 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1217,31 +1217,60 @@ int main(int argc, char** argv)
12171217

12181218
/* run as a daemon */
12191219
if (ret == WS_SUCCESS && isDaemon) {
1220+
pid_t p;
1221+
12201222
#ifdef __unix__
12211223
/* Daemonizing in POSIX, so set a syslog based log */
12221224
wolfSSH_SetLoggingCb(SyslogCb);
12231225
#endif
1224-
pid_t p;
1225-
12261226
p = fork();
12271227
if (p < 0) {
12281228
fprintf(stderr, "Failed to fork process\n");
1229-
ret = WS_FATAL_ERROR;
1229+
exit(EXIT_FAILURE);
1230+
}
1231+
if (p > 0) {
1232+
exit(EXIT_SUCCESS); /* stop parent process */
12301233
}
12311234

1232-
if (ret == WS_SUCCESS) {
1235+
if (setsid() < 0) {
1236+
fprintf(stderr, "Failed to set a new session");
1237+
ret = WS_FATAL_ERROR;
1238+
}
1239+
else {
1240+
signal(SIGCHLD, ConnClose);
1241+
p = fork();
1242+
if (p < 0) {
1243+
fprintf(stderr, "Failed to fork process\n");
1244+
exit(EXIT_FAILURE);
1245+
}
12331246
if (p > 0) {
1234-
exit(0); /* stop parent process */
1247+
exit(EXIT_SUCCESS);
12351248
}
12361249

1237-
if (setsid() < 0) {
1238-
fprintf(stderr, "Failed to set a new session");
1250+
umask(0);
1251+
if (chdir("/") < 0) {
12391252
ret = WS_FATAL_ERROR;
12401253
}
1254+
1255+
if (ret == WS_SUCCESS) {
1256+
int fd;
1257+
1258+
fd = open("/dev/null", O_RDWR);
1259+
if (fd < 0) {
1260+
ret = WS_FATAL_ERROR;
1261+
}
1262+
else {
1263+
if (dup2(fd, STDIN_FILENO) < 0 ||
1264+
dup2(fd, STDOUT_FILENO) < 0 ||
1265+
dup2(fd, STDERR_FILENO) < 0) {
1266+
ret = WS_FATAL_ERROR;
1267+
}
1268+
close(fd);
1269+
}
1270+
}
12411271
}
12421272
}
12431273

1244-
signal(SIGCHLD, ConnClose);
12451274
if (ret == WS_SUCCESS) {
12461275
wolfSSH_Log(WS_LOG_INFO, "[SSHD] Starting to listen on port %d", port);
12471276
tcp_listen(&listenFd, &port, 1);

0 commit comments

Comments
 (0)