1/*
2 Simple DirectMedia Layer
3 Copyright (C) 1997-2021 Sam Lantinga <slouken@libsdl.org>
4
5 This software is provided 'as-is', without any express or implied
6 warranty. In no event will the authors be held liable for any damages
7 arising from the use of this software.
8
9 Permission is granted to anyone to use this software for any purpose,
10 including commercial applications, and to alter it and redistribute it
11 freely, subject to the following restrictions:
12
13 1. The origin of this software must not be misrepresented; you must not
14 claim that you wrote the original software. If you use this software
15 in a product, an acknowledgment in the product documentation would be
16 appreciated but is not required.
17 2. Altered source versions must be plainly marked as such, and must not be
18 misrepresented as being the original software.
19 3. This notice may not be removed or altered from any source distribution.
20*/
21
22#include "../SDL_sysurl.h"
23
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
27#include <unistd.h>
28#include <sys/wait.h>
29#include <errno.h>
30
31int
32SDL_SYS_OpenURL(const char *url)
33{
34 const pid_t pid1 = fork();
35 if (pid1 == 0) { /* child process */
36 /* Notice this is vfork and not fork! */
37 const pid_t pid2 = vfork();
38 if (pid2 == 0) { /* Grandchild process will try to launch the url */
39 execlp("xdg-open", "xdg-open", url, NULL);
40 _exit(EXIT_FAILURE);
41 } else if (pid2 < 0) { /* There was an error forking */
42 _exit(EXIT_FAILURE);
43 } else {
44 /* Child process doesn't wait for possibly-blocking grandchild. */
45 _exit(EXIT_SUCCESS);
46 }
47 } else if (pid1 < 0) {
48 return SDL_SetError("fork() failed: %s", strerror(errno));
49 } else {
50 int status;
51 if (waitpid(pid1, &status, 0) == pid1) {
52 if (WIFEXITED(status)) {
53 if (WEXITSTATUS(status) == 0) {
54 return 0; /* success! */
55 } else {
56 return SDL_SetError("xdg-open reported error or failed to launch: %d", WEXITSTATUS(status));
57 }
58 } else {
59 return SDL_SetError("xdg-open failed for some reason");
60 }
61 } else {
62 return SDL_SetError("Waiting on xdg-open failed: %s", strerror(errno));
63 }
64 }
65
66 return 0;
67}
68
69/* vi: set ts=4 sw=4 expandtab: */
70
71