Handle fork() failures more gracefully

This commit is contained in:
Kovid Goyal 2018-01-05 13:57:49 +05:30
parent e03c713294
commit f06f871dfc
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C

View File

@ -51,7 +51,8 @@ spawn(PyObject *self UNUSED, PyObject *args) {
#define exit_on_err(m) { write_to_stderr(m); write_to_stderr(": "); write_to_stderr(strerror(errno)); exit(EXIT_FAILURE); } #define exit_on_err(m) { write_to_stderr(m); write_to_stderr(": "); write_to_stderr(strerror(errno)); exit(EXIT_FAILURE); }
pid_t pid = fork(); pid_t pid = fork();
if (pid == 0) { switch(pid) {
case 0:
// child // child
// Use only signal-safe functions (man 7 signal-safety) // Use only signal-safe functions (man 7 signal-safety)
if (chdir(cwd) != 0) { if (chdir("/") != 0) {} }; // ignore failure to chdir to / if (chdir(cwd) != 0) { if (chdir("/") != 0) {} }; // ignore failure to chdir to /
@ -85,11 +86,17 @@ spawn(PyObject *self UNUSED, PyObject *args) {
write_to_stderr("\nPress Enter to exit.\n"); write_to_stderr("\nPress Enter to exit.\n");
execlp("sh", "sh", "-c", "read w", NULL); execlp("sh", "sh", "-c", "read w", NULL);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} else { break;
free(argv); case -1:
free(env); PyErr_SetFromErrno(PyExc_OSError);
break;
default:
break;
} }
#undef exit_on_err #undef exit_on_err
free(argv);
free(env);
if (pid == -1) return NULL;
return PyLong_FromLong(pid); return PyLong_FromLong(pid);
} }