1 /* Interfaces to system-dependent kernel and library entries.
2 Copyright (C) 1985-1988, 1993-1995, 1999-2012
3 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
28 #endif /* HAVE_PWD_H */
32 #include <allocator.h>
33 #include <careadlinkat.h>
34 #include <ignore-value.h>
37 #include "sysselect.h"
38 #include "blockinput.h"
41 #include <sys/sysctl.h>
43 #include <sys/resource.h> */
48 #include <sys/sysctl.h>
53 #define write sys_write
55 #endif /* not WINDOWSNT */
57 #include <sys/types.h>
64 #define setpgrp setpgid
68 /* Get SI_SRPC_DOMAIN, if it is available. */
69 #ifdef HAVE_SYS_SYSTEMINFO_H
70 #include <sys/systeminfo.h>
73 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
77 #include <sys/param.h>
86 #ifdef HAVE_SYS_UTSNAME_H
87 #include <sys/utsname.h>
89 #endif /* HAVE_SYS_UTSNAME_H */
94 #include "termhooks.h"
97 #include "dispextern.h"
99 #include "cm.h" /* for reset_sys_modes */
103 /* In process.h which conflicts with the local copy. */
105 int _cdecl
_spawnlp (int, const char *, const char *, ...);
106 int _cdecl
_getpid (void);
107 extern char *getwd (char *);
110 #include "syssignal.h"
117 #ifndef HAVE_STRUCT_UTIMBUF
118 /* We want to use utime rather than utimes, but we couldn't find the
119 structure declaration. We'll use the traditional one. */
127 static int emacs_get_tty (int, struct emacs_tty
*);
128 static int emacs_set_tty (int, struct emacs_tty
*, int);
129 #if defined TIOCNOTTY || defined USG5 || defined CYGWIN
130 static void croak (char *) NO_RETURN
;
133 /* Declare here, including term.h is problematic on some systems. */
134 extern void tputs (const char *, int, int (*)(int));
136 static const int baud_convert
[] =
138 0, 50, 75, 110, 135, 150, 200, 300, 600, 1200,
139 1800, 2400, 4800, 9600, 19200, 38400
143 #if !defined (HAVE_GET_CURRENT_DIR_NAME) || defined (BROKEN_GET_CURRENT_DIR_NAME)
145 /* Return the current working directory. Returns NULL on errors.
146 Any other returned value must be freed with free. This is used
147 only when get_current_dir_name is not defined on the system. */
149 get_current_dir_name (void)
153 struct stat dotstat
, pwdstat
;
154 /* If PWD is accurate, use it instead of calling getwd. PWD is
155 sometimes a nicer name, and using it may avoid a fatal error if a
156 parent directory is searchable but not readable. */
157 if ((pwd
= getenv ("PWD")) != 0
158 && (IS_DIRECTORY_SEP (*pwd
) || (*pwd
&& IS_DEVICE_SEP (pwd
[1])))
159 && stat (pwd
, &pwdstat
) == 0
160 && stat (".", &dotstat
) == 0
161 && dotstat
.st_ino
== pwdstat
.st_ino
162 && dotstat
.st_dev
== pwdstat
.st_dev
164 && strlen (pwd
) < MAXPATHLEN
168 buf
= (char *) malloc (strlen (pwd
) + 1);
176 size_t buf_size
= 1024;
177 buf
= (char *) malloc (buf_size
);
182 if (getcwd (buf
, buf_size
) == buf
)
186 int tmp_errno
= errno
;
192 buf
= (char *) realloc (buf
, buf_size
);
200 /* We need MAXPATHLEN here. */
201 buf
= (char *) malloc (MAXPATHLEN
+ 1);
204 if (getwd (buf
) == NULL
)
206 int tmp_errno
= errno
;
218 /* Discard pending input on all input descriptors. */
221 discard_tty_input (void)
224 struct emacs_tty buf
;
229 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
230 while (dos_keyread () != -1)
232 #else /* not MSDOS */
234 struct tty_display_info
*tty
;
235 for (tty
= tty_list
; tty
; tty
= tty
->next
)
237 if (tty
->input
) /* Is the device suspended? */
239 emacs_get_tty (fileno (tty
->input
), &buf
);
240 emacs_set_tty (fileno (tty
->input
), &buf
, 0);
244 #endif /* not MSDOS */
245 #endif /* not WINDOWSNT */
251 /* Arrange for character C to be read as the next input from
253 XXX What if we have multiple ttys?
259 if (! FRAME_TERMCAP_P (SELECTED_FRAME ()))
262 /* Should perhaps error if in batch mode */
264 ioctl (fileno (CURTTY()->input
), TIOCSTI
, &c
);
265 #else /* no TIOCSTI */
266 error ("Cannot stuff terminal input characters in this version of Unix");
267 #endif /* no TIOCSTI */
273 init_baud_rate (int fd
)
283 #else /* not DOS_NT */
288 emacs_ospeed
= cfgetospeed (&sg
);
289 #endif /* not DOS_NT */
292 baud_rate
= (emacs_ospeed
< sizeof baud_convert
/ sizeof baud_convert
[0]
293 ? baud_convert
[emacs_ospeed
] : 9600);
300 /* Set nonzero to make following function work under dbx
301 (at least for bsd). */
302 int wait_debugging EXTERNALLY_VISIBLE
;
307 wait_for_termination_1 (int pid
, int interruptible
)
311 #if (defined (BSD_SYSTEM) || defined (HPUX)) && !defined (__GNU__)
312 /* Note that kill returns -1 even if the process is just a zombie now.
313 But inevitably a SIGCHLD interrupt should be generated
314 and child_sig will do wait3 and make the process go away. */
315 /* There is some indication that there is a bug involved with
316 termination of subprocesses, perhaps involving a kernel bug too,
317 but no idea what it is. Just as a hunch we signal SIGCHLD to see
318 if that causes the problem to go away or get worse. */
319 sigsetmask (sigmask (SIGCHLD
));
320 if (0 > kill (pid
, 0))
322 sigsetmask (SIGEMPTYMASK
);
323 kill (getpid (), SIGCHLD
);
329 sigpause (SIGEMPTYMASK
);
330 #else /* not BSD_SYSTEM, and not HPUX version >= 6 */
334 #else /* not WINDOWSNT */
335 sigblock (sigmask (SIGCHLD
));
337 if (kill (pid
, 0) == -1 && errno
== ESRCH
)
339 sigunblock (sigmask (SIGCHLD
));
343 sigsuspend (&empty_mask
);
344 #endif /* not WINDOWSNT */
345 #endif /* not BSD_SYSTEM, and not HPUX version >= 6 */
351 /* Wait for subprocess with process id `pid' to terminate and
352 make sure it will get eliminated (not remain forever as a zombie) */
355 wait_for_termination (int pid
)
357 wait_for_termination_1 (pid
, 0);
360 /* Like the above, but allow keyboard interruption. */
362 interruptible_wait_for_termination (int pid
)
364 wait_for_termination_1 (pid
, 1);
368 * flush any pending output
369 * (may flush input as well; it does not matter the way we use it)
373 flush_pending_output (int channel
)
375 /* FIXME: maybe this function should be removed */
378 /* Set up the terminal at the other end of a pseudo-terminal that
379 we will be controlling an inferior through.
380 It should not echo or do line-editing, since that is done
381 in Emacs. No padding needed for insertion into an Emacs buffer. */
384 child_setup_tty (int out
)
389 emacs_get_tty (out
, &s
);
390 s
.main
.c_oflag
|= OPOST
; /* Enable output postprocessing */
391 s
.main
.c_oflag
&= ~ONLCR
; /* Disable map of NL to CR-NL on output */
393 /* http://lists.gnu.org/archive/html/emacs-devel/2008-05/msg00406.html
394 Some versions of GNU Hurd do not have FFDLY? */
396 s
.main
.c_oflag
&= ~(NLDLY
|CRDLY
|TABDLY
|BSDLY
|VTDLY
|FFDLY
);
397 /* No output delays */
399 s
.main
.c_oflag
&= ~(NLDLY
|CRDLY
|TABDLY
|BSDLY
|VTDLY
);
400 /* No output delays */
403 s
.main
.c_lflag
&= ~ECHO
; /* Disable echo */
404 s
.main
.c_lflag
|= ISIG
; /* Enable signals */
406 s
.main
.c_iflag
&= ~IUCLC
; /* Disable downcasing on input. */
409 s
.main
.c_iflag
&= ~ISTRIP
; /* don't strip 8th bit on input */
412 s
.main
.c_oflag
&= ~OLCUC
; /* Disable upcasing on output. */
414 s
.main
.c_oflag
&= ~TAB3
; /* Disable tab expansion */
415 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CSIZE
) | CS8
; /* Don't strip 8th bit */
416 s
.main
.c_cc
[VERASE
] = CDISABLE
; /* disable erase processing */
417 s
.main
.c_cc
[VKILL
] = CDISABLE
; /* disable kill processing */
420 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CBAUD
) | B9600
; /* baud rate sanity */
423 #ifdef SIGNALS_VIA_CHARACTERS
424 /* the QUIT and INTR character are used in process_send_signal
425 so set them here to something useful. */
426 if (s
.main
.c_cc
[VQUIT
] == CDISABLE
)
427 s
.main
.c_cc
[VQUIT
] = '\\'&037; /* Control-\ */
428 if (s
.main
.c_cc
[VINTR
] == CDISABLE
)
429 s
.main
.c_cc
[VINTR
] = 'C'&037; /* Control-C */
430 #endif /* not SIGNALS_VIA_CHARACTERS */
433 /* Also, PTY overloads NUL and BREAK.
434 don't ignore break, but don't signal either, so it looks like NUL. */
435 s
.main
.c_iflag
&= ~IGNBRK
;
436 s
.main
.c_iflag
&= ~BRKINT
;
437 /* rms: Formerly it set s.main.c_cc[VINTR] to 0377 here
438 unconditionally. Then a SIGNALS_VIA_CHARACTERS conditional
439 would force it to 0377. That looks like duplicated code. */
440 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CBAUD
) | B9600
; /* baud rate sanity */
443 /* We originally enabled ICANON (and set VEOF to 04), and then had
444 process.c send additional EOF chars to flush the output when faced
445 with long lines, but this leads to weird effects when the
446 subprocess has disabled ICANON and ends up seeing those spurious
447 extra EOFs. So we don't send EOFs any more in
448 process.c:send_process. First we tried to disable ICANON by
449 default, so if a subsprocess sets up ICANON, it's his problem (or
450 the Elisp package that talks to it) to deal with lines that are
451 too long. But this disables some features, such as the ability
452 to send EOF signals. So we re-enabled ICANON but there is no
453 more "send eof to flush" going on (which is wrong and unportable
454 in itself). The correct way to handle too much output is to
455 buffer what could not be written and then write it again when
456 select returns ok for writing. This has it own set of
457 problems. Write is now asynchronous, is that a problem? How much
458 do we buffer, and what do we do when that limit is reached? */
460 s
.main
.c_lflag
|= ICANON
; /* Enable line editing and eof processing */
461 s
.main
.c_cc
[VEOF
] = 'D'&037; /* Control-D */
462 #if 0 /* These settings only apply to non-ICANON mode. */
463 s
.main
.c_cc
[VMIN
] = 1;
464 s
.main
.c_cc
[VTIME
] = 0;
467 emacs_set_tty (out
, &s
, 0);
468 #endif /* not WINDOWSNT */
470 #endif /* not MSDOS */
473 /* Record a signal code and the handler for it. */
477 void (*handler
) (int);
480 static void save_signal_handlers (struct save_signal
*);
481 static void restore_signal_handlers (struct save_signal
*);
483 /* Suspend the Emacs process; give terminal to its superior. */
488 #if defined (SIGTSTP) && !defined (MSDOS)
491 int pgrp
= EMACS_GETPGRP (0);
492 EMACS_KILLPG (pgrp
, SIGTSTP
);
495 #else /* No SIGTSTP */
496 /* On a system where suspending is not implemented,
497 instead fork a subshell and let it talk directly to the terminal
501 #endif /* no SIGTSTP */
504 /* Fork a subshell. */
509 #ifdef DOS_NT /* Demacs 1.1.2 91/10/20 Manabu Higashida */
511 char oldwd
[MAXPATHLEN
+1]; /* Fixed length is safe on MSDOS. */
514 struct save_signal saved_handlers
[5];
516 unsigned char *volatile str_volatile
= 0;
520 saved_handlers
[0].code
= SIGINT
;
521 saved_handlers
[1].code
= SIGQUIT
;
522 saved_handlers
[2].code
= SIGTERM
;
524 saved_handlers
[3].code
= SIGIO
;
525 saved_handlers
[4].code
= 0;
527 saved_handlers
[3].code
= 0;
530 /* Mentioning current_buffer->buffer would mean including buffer.h,
531 which somehow wedges the hp compiler. So instead... */
533 dir
= intern ("default-directory");
534 if (NILP (Fboundp (dir
)))
536 dir
= Fsymbol_value (dir
);
540 dir
= expand_and_dir_to_file (Funhandled_file_name_directory (dir
), Qnil
);
541 str_volatile
= str
= (unsigned char *) alloca (SCHARS (dir
) + 2);
543 memcpy (str
, SDATA (dir
), len
);
544 if (str
[len
- 1] != '/') str
[len
++] = '/';
550 save_signal_handlers (saved_handlers
);
551 synch_process_alive
= 1;
555 error ("Can't spawn subshell");
562 #ifdef DOS_NT /* MW, Aug 1993 */
565 sh
= (char *) egetenv ("SUSPEND"); /* KFS, 1994-12-14 */
568 sh
= (char *) egetenv ("SHELL");
572 /* Use our buffer's default directory for the subshell. */
574 if (str
&& chdir ((char *) str
) != 0)
577 ignore_value (write (1, "Can't chdir\n", 12));
582 close_process_descs (); /* Close Emacs's pipes/ptys */
584 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
586 char *epwd
= getenv ("PWD");
587 char old_pwd
[MAXPATHLEN
+1+4];
589 /* If PWD is set, pass it with corrected value. */
592 strcpy (old_pwd
, epwd
);
593 if (str
[len
- 1] == '/')
595 setenv ("PWD", str
, 1);
598 chdir (oldwd
); /* FIXME: Do the right thing on chdir failure. */
600 putenv (old_pwd
); /* restore previous value */
602 #else /* not MSDOS */
604 /* Waits for process completion */
605 pid
= _spawnlp (_P_WAIT
, sh
, sh
, NULL
);
606 chdir (oldwd
); /* FIXME: Do the right thing on chdir failure. */
608 write (1, "Can't execute subshell", 22);
609 #else /* not WINDOWSNT */
610 execlp (sh
, sh
, (char *) 0);
611 ignore_value (write (1, "Can't execute subshell", 22));
613 #endif /* not WINDOWSNT */
614 #endif /* not MSDOS */
617 /* Do this now if we did not do it before. */
619 save_signal_handlers (saved_handlers
);
620 synch_process_alive
= 1;
624 wait_for_termination (pid
);
626 restore_signal_handlers (saved_handlers
);
627 synch_process_alive
= 0;
631 save_signal_handlers (struct save_signal
*saved_handlers
)
633 while (saved_handlers
->code
)
635 saved_handlers
->handler
636 = (void (*) (int)) signal (saved_handlers
->code
, SIG_IGN
);
642 restore_signal_handlers (struct save_signal
*saved_handlers
)
644 while (saved_handlers
->code
)
646 signal (saved_handlers
->code
, saved_handlers
->handler
);
652 /* If SIGIO is broken, don't do anything. */
669 unrequest_sigio (void)
676 static int old_fcntl_flags
[MAXDESC
];
682 old_fcntl_flags
[fd
] = fcntl (fd
, F_GETFL
, 0) & ~FASYNC
;
683 fcntl (fd
, F_SETFL
, old_fcntl_flags
[fd
] | FASYNC
);
685 interrupts_deferred
= 0;
692 fcntl (fd
, F_SETFL
, old_fcntl_flags
[fd
]);
696 #ifdef FASYNC /* F_SETFL does not imply existence of FASYNC */
697 /* XXX Uhm, FASYNC is not used anymore here. */
698 /* XXX Yeah, but you need it for SIGIO, don't you? */
707 sigunblock (sigmask (SIGWINCH
));
709 sigunblock (sigmask (SIGIO
));
711 interrupts_deferred
= 0;
715 unrequest_sigio (void)
720 #if 0 /* XXX What's wrong with blocking SIGIO under X? */
726 sigblock (sigmask (SIGWINCH
));
728 sigblock (sigmask (SIGIO
));
729 interrupts_deferred
= 1;
732 #else /* no FASYNC */
738 if (noninteractive
|| read_socket_hook
)
741 croak ("request_sigio");
745 unrequest_sigio (void)
747 if (noninteractive
|| read_socket_hook
)
750 croak ("unrequest_sigio");
759 /* Getting and setting emacs_tty structures. */
761 /* Set *TC to the parameters associated with the terminal FD.
762 Return zero if all's well, or -1 if we ran into an error we
763 couldn't deal with. */
765 emacs_get_tty (int fd
, struct emacs_tty
*settings
)
767 /* Retrieve the primary parameters - baud rate, character size, etcetera. */
769 /* We have those nifty POSIX tcmumbleattr functions. */
770 memset (&settings
->main
, 0, sizeof (settings
->main
));
771 if (tcgetattr (fd
, &settings
->main
) < 0)
775 /* We have survived the tempest. */
780 /* Set the parameters of the tty on FD according to the contents of
781 *SETTINGS. If FLUSHP is non-zero, we discard input.
782 Return 0 if all went well, and -1 if anything failed. */
785 emacs_set_tty (int fd
, struct emacs_tty
*settings
, int flushp
)
787 /* Set the primary parameters - baud rate, character size, etcetera. */
790 /* We have those nifty POSIX tcmumbleattr functions.
791 William J. Smith <wjs@wiis.wang.com> writes:
792 "POSIX 1003.1 defines tcsetattr to return success if it was
793 able to perform any of the requested actions, even if some
794 of the requested actions could not be performed.
795 We must read settings back to ensure tty setup properly.
796 AIX requires this to keep tty from hanging occasionally." */
797 /* This make sure that we don't loop indefinitely in here. */
798 for (i
= 0 ; i
< 10 ; i
++)
799 if (tcsetattr (fd
, flushp
? TCSAFLUSH
: TCSADRAIN
, &settings
->main
) < 0)
810 memset (&new, 0, sizeof (new));
811 /* Get the current settings, and see if they're what we asked for. */
812 tcgetattr (fd
, &new);
813 /* We cannot use memcmp on the whole structure here because under
814 * aix386 the termios structure has some reserved field that may
817 if ( new.c_iflag
== settings
->main
.c_iflag
818 && new.c_oflag
== settings
->main
.c_oflag
819 && new.c_cflag
== settings
->main
.c_cflag
820 && new.c_lflag
== settings
->main
.c_lflag
821 && memcmp (new.c_cc
, settings
->main
.c_cc
, NCCS
) == 0)
828 /* We have survived the tempest. */
835 static int old_fcntl_owner
[MAXDESC
];
836 #endif /* F_SETOWN */
838 /* This may also be defined in stdio,
839 but if so, this does no harm,
840 and using the same name avoids wasting the other one's space. */
843 unsigned char _sobuf
[BUFSIZ
+8];
848 /* Initialize the terminal mode on all tty devices that are currently
852 init_all_sys_modes (void)
854 struct tty_display_info
*tty
;
855 for (tty
= tty_list
; tty
; tty
= tty
->next
)
856 init_sys_modes (tty
);
859 /* Initialize the terminal mode on the given tty device. */
862 init_sys_modes (struct tty_display_info
*tty_out
)
864 struct emacs_tty tty
;
865 Lisp_Object terminal
;
867 Vtty_erase_char
= Qnil
;
872 if (!tty_out
->output
)
873 return; /* The tty is suspended. */
875 if (! tty_out
->old_tty
)
876 tty_out
->old_tty
= (struct emacs_tty
*) xmalloc (sizeof (struct emacs_tty
));
878 emacs_get_tty (fileno (tty_out
->input
), tty_out
->old_tty
);
880 tty
= *tty_out
->old_tty
;
882 #if !defined (DOS_NT)
883 XSETINT (Vtty_erase_char
, tty
.main
.c_cc
[VERASE
]);
885 tty
.main
.c_iflag
|= (IGNBRK
); /* Ignore break condition */
886 tty
.main
.c_iflag
&= ~ICRNL
; /* Disable map of CR to NL on input */
887 #ifdef INLCR /* I'm just being cautious,
888 since I can't check how widespread INLCR is--rms. */
889 tty
.main
.c_iflag
&= ~INLCR
; /* Disable map of NL to CR on input */
892 tty
.main
.c_iflag
&= ~ISTRIP
; /* don't strip 8th bit on input */
894 tty
.main
.c_lflag
&= ~ECHO
; /* Disable echo */
895 tty
.main
.c_lflag
&= ~ICANON
; /* Disable erase/kill processing */
897 tty
.main
.c_lflag
&= ~IEXTEN
; /* Disable other editing characters. */
899 tty
.main
.c_lflag
|= ISIG
; /* Enable signals */
900 if (tty_out
->flow_control
)
902 tty
.main
.c_iflag
|= IXON
; /* Enable start/stop output control */
904 tty
.main
.c_iflag
&= ~IXANY
;
908 tty
.main
.c_iflag
&= ~IXON
; /* Disable start/stop output control */
909 tty
.main
.c_oflag
&= ~ONLCR
; /* Disable map of NL to CR-NL
911 tty
.main
.c_oflag
&= ~TAB3
; /* Disable tab expansion */
913 if (tty_out
->meta_key
)
915 tty
.main
.c_cflag
|= CS8
; /* allow 8th bit on input */
916 tty
.main
.c_cflag
&= ~PARENB
;/* Don't check parity */
920 XSETTERMINAL(terminal
, tty_out
->terminal
);
921 if (!NILP (Fcontrolling_tty_p (terminal
)))
923 tty
.main
.c_cc
[VINTR
] = quit_char
; /* C-g (usually) gives SIGINT */
924 /* Set up C-g for both SIGQUIT and SIGINT.
925 We don't know which we will get, but we handle both alike
926 so which one it really gives us does not matter. */
927 tty
.main
.c_cc
[VQUIT
] = quit_char
;
931 /* We normally don't get interrupt or quit signals from tty
932 devices other than our controlling terminal; therefore,
933 we must handle C-g as normal input. Unfortunately, this
934 means that the interrupt and quit feature must be
935 disabled on secondary ttys, or we would not even see the
938 Note that even though emacsclient could have special code
939 to pass SIGINT to Emacs, we should _not_ enable
940 interrupt/quit keys for emacsclient frames. This means
941 that we can't break out of loops in C code from a
942 secondary tty frame, but we can always decide what
943 display the C-g came from, which is more important from a
944 usability point of view. (Consider the case when two
945 people work together using the same Emacs instance.) */
946 tty
.main
.c_cc
[VINTR
] = CDISABLE
;
947 tty
.main
.c_cc
[VQUIT
] = CDISABLE
;
949 tty
.main
.c_cc
[VMIN
] = 1; /* Input should wait for at least 1 char */
950 tty
.main
.c_cc
[VTIME
] = 0; /* no matter how long that takes. */
952 tty
.main
.c_cc
[VSWTCH
] = CDISABLE
; /* Turn off shell layering use
957 tty
.main
.c_cc
[VSUSP
] = CDISABLE
; /* Turn off handling of C-z. */
960 tty
.main
.c_cc
[V_DSUSP
] = CDISABLE
; /* Turn off handling of C-y. */
962 #ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP. */
963 tty
.main
.c_cc
[VDSUSP
] = CDISABLE
;
966 tty
.main
.c_cc
[VLNEXT
] = CDISABLE
;
969 tty
.main
.c_cc
[VREPRINT
] = CDISABLE
;
970 #endif /* VREPRINT */
972 tty
.main
.c_cc
[VWERASE
] = CDISABLE
;
975 tty
.main
.c_cc
[VDISCARD
] = CDISABLE
;
976 #endif /* VDISCARD */
978 if (tty_out
->flow_control
)
981 tty
.main
.c_cc
[VSTART
] = '\021';
984 tty
.main
.c_cc
[VSTOP
] = '\023';
990 tty
.main
.c_cc
[VSTART
] = CDISABLE
;
993 tty
.main
.c_cc
[VSTOP
] = CDISABLE
;
998 tty
.main
.c_cc
[VSTRT
] = CDISABLE
;
999 tty
.main
.c_cc
[VSTOP
] = CDISABLE
;
1000 tty
.main
.c_cc
[VSUSP
] = CDISABLE
;
1001 tty
.main
.c_cc
[VDSUSP
] = CDISABLE
;
1002 if (tty_out
->flow_control
)
1005 tty
.main
.c_cc
[VSTART
] = '\021';
1008 tty
.main
.c_cc
[VSTOP
] = '\023';
1011 /* Also, PTY overloads NUL and BREAK.
1012 don't ignore break, but don't signal either, so it looks like NUL.
1013 This really serves a purpose only if running in an XTERM window
1014 or via TELNET or the like, but does no harm elsewhere. */
1015 tty
.main
.c_iflag
&= ~IGNBRK
;
1016 tty
.main
.c_iflag
&= ~BRKINT
;
1018 #endif /* not DOS_NT */
1020 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
1021 if (!tty_out
->term_initted
)
1022 internal_terminal_init ();
1023 dos_ttraw (tty_out
);
1026 emacs_set_tty (fileno (tty_out
->input
), &tty
, 0);
1028 /* This code added to insure that, if flow-control is not to be used,
1029 we have an unlocked terminal at the start. */
1032 if (!tty_out
->flow_control
) ioctl (fileno (tty_out
->input
), TCXONC
, 1);
1035 if (!tty_out
->flow_control
) ioctl (fileno (tty_out
->input
), TIOCSTART
, 0);
1038 #if !defined (DOS_NT)
1040 if (!tty_out
->flow_control
) tcflow (fileno (tty_out
->input
), TCOON
);
1045 #ifdef F_GETOWN /* F_SETFL does not imply existence of F_GETOWN */
1046 if (interrupt_input
)
1048 old_fcntl_owner
[fileno (tty_out
->input
)] =
1049 fcntl (fileno (tty_out
->input
), F_GETOWN
, 0);
1050 fcntl (fileno (tty_out
->input
), F_SETOWN
, getpid ());
1051 init_sigio (fileno (tty_out
->input
));
1053 if (gpm_tty
== tty_out
)
1055 /* Arrange for mouse events to give us SIGIO signals. */
1056 fcntl (gpm_fd
, F_SETOWN
, getpid ());
1057 fcntl (gpm_fd
, F_SETFL
, fcntl (gpm_fd
, F_GETFL
, 0) | O_NONBLOCK
);
1058 init_sigio (gpm_fd
);
1060 #endif /* HAVE_GPM */
1062 #endif /* F_GETOWN */
1063 #endif /* F_SETFL */
1066 /* This symbol is defined on recent USG systems.
1067 Someone says without this call USG won't really buffer the file
1068 even with a call to setbuf. */
1069 setvbuf (tty_out
->output
, (char *) _sobuf
, _IOFBF
, sizeof _sobuf
);
1071 setbuf (tty_out
->output
, (char *) _sobuf
);
1074 if (tty_out
->terminal
->set_terminal_modes_hook
)
1075 tty_out
->terminal
->set_terminal_modes_hook (tty_out
->terminal
);
1077 if (!tty_out
->term_initted
)
1079 Lisp_Object tail
, frame
;
1080 FOR_EACH_FRAME (tail
, frame
)
1082 /* XXX This needs to be revised. */
1083 if (FRAME_TERMCAP_P (XFRAME (frame
))
1084 && FRAME_TTY (XFRAME (frame
)) == tty_out
)
1085 init_frame_faces (XFRAME (frame
));
1089 if (tty_out
->term_initted
&& no_redraw_on_reenter
)
1091 /* We used to call "direct_output_forward_char(0)" here,
1092 but it's not clear why, since it may not do anything anyway. */
1096 Lisp_Object tail
, frame
;
1098 FOR_EACH_FRAME (tail
, frame
)
1100 if ((FRAME_TERMCAP_P (XFRAME (frame
))
1101 || FRAME_MSDOS_P (XFRAME (frame
)))
1102 && FRAME_TTY (XFRAME (frame
)) == tty_out
)
1103 FRAME_GARBAGED_P (XFRAME (frame
)) = 1;
1107 tty_out
->term_initted
= 1;
1110 /* Return nonzero if safe to use tabs in output.
1111 At the time this is called, init_sys_modes has not been done yet. */
1114 tabs_safe_p (int fd
)
1116 struct emacs_tty etty
;
1118 emacs_get_tty (fd
, &etty
);
1121 return ((etty
.main
.c_oflag
& TABDLY
) != TAB3
);
1122 #else /* not TABDLY */
1124 #endif /* not TABDLY */
1130 /* Get terminal size from system.
1131 Store number of lines into *HEIGHTP and width into *WIDTHP.
1132 We store 0 if there's no valid information. */
1135 get_tty_size (int fd
, int *widthp
, int *heightp
)
1137 #if defined TIOCGWINSZ
1140 struct winsize size
;
1142 if (ioctl (fd
, TIOCGWINSZ
, &size
) == -1)
1143 *widthp
= *heightp
= 0;
1146 *widthp
= size
.ws_col
;
1147 *heightp
= size
.ws_row
;
1150 #elif defined TIOCGSIZE
1152 /* SunOS - style. */
1153 struct ttysize size
;
1155 if (ioctl (fd
, TIOCGSIZE
, &size
) == -1)
1156 *widthp
= *heightp
= 0;
1159 *widthp
= size
.ts_cols
;
1160 *heightp
= size
.ts_lines
;
1163 #elif defined WINDOWSNT
1165 CONSOLE_SCREEN_BUFFER_INFO info
;
1166 if (GetConsoleScreenBufferInfo (GetStdHandle (STD_OUTPUT_HANDLE
), &info
))
1168 *widthp
= info
.srWindow
.Right
- info
.srWindow
.Left
+ 1;
1169 *heightp
= info
.srWindow
.Bottom
- info
.srWindow
.Top
+ 1;
1172 *widthp
= *heightp
= 0;
1176 *widthp
= ScreenCols ();
1177 *heightp
= ScreenRows ();
1179 #else /* system doesn't know size */
1187 /* Set the logical window size associated with descriptor FD
1188 to HEIGHT and WIDTH. This is used mainly with ptys. */
1191 set_window_size (int fd
, int height
, int width
)
1196 struct winsize size
;
1197 size
.ws_row
= height
;
1198 size
.ws_col
= width
;
1200 if (ioctl (fd
, TIOCSWINSZ
, &size
) == -1)
1201 return 0; /* error */
1208 /* SunOS - style. */
1209 struct ttysize size
;
1210 size
.ts_lines
= height
;
1211 size
.ts_cols
= width
;
1213 if (ioctl (fd
, TIOCGSIZE
, &size
) == -1)
1219 #endif /* not SunOS-style */
1220 #endif /* not BSD-style */
1225 /* Prepare all terminal devices for exiting Emacs. */
1228 reset_all_sys_modes (void)
1230 struct tty_display_info
*tty
;
1231 for (tty
= tty_list
; tty
; tty
= tty
->next
)
1232 reset_sys_modes (tty
);
1235 /* Prepare the terminal for closing it; move the cursor to the
1236 bottom of the frame, turn off interrupt-driven I/O, etc. */
1239 reset_sys_modes (struct tty_display_info
*tty_out
)
1246 if (!tty_out
->term_initted
)
1249 if (!tty_out
->output
)
1250 return; /* The tty is suspended. */
1252 /* Go to and clear the last line of the terminal. */
1254 cmgoto (tty_out
, FrameRows (tty_out
) - 1, 0);
1256 /* Code adapted from tty_clear_end_of_line. */
1257 if (tty_out
->TS_clr_line
)
1259 emacs_tputs (tty_out
, tty_out
->TS_clr_line
, 1, cmputc
);
1262 { /* have to do it the hard way */
1264 tty_turn_off_insert (tty_out
);
1266 for (i
= curX (tty_out
); i
< FrameCols (tty_out
) - 1; i
++)
1268 fputc (' ', tty_out
->output
);
1272 cmgoto (tty_out
, FrameRows (tty_out
) - 1, 0);
1273 fflush (tty_out
->output
);
1275 if (tty_out
->terminal
->reset_terminal_modes_hook
)
1276 tty_out
->terminal
->reset_terminal_modes_hook (tty_out
->terminal
);
1279 /* Avoid possible loss of output when changing terminal modes. */
1280 fsync (fileno (tty_out
->output
));
1284 #ifdef F_SETOWN /* F_SETFL does not imply existence of F_SETOWN */
1285 if (interrupt_input
)
1287 reset_sigio (fileno (tty_out
->input
));
1288 fcntl (fileno (tty_out
->input
), F_SETOWN
,
1289 old_fcntl_owner
[fileno (tty_out
->input
)]);
1291 #endif /* F_SETOWN */
1293 fcntl (fileno (tty_out
->input
), F_SETFL
,
1294 fcntl (fileno (tty_out
->input
), F_GETFL
, 0) & ~O_NDELAY
);
1296 #endif /* F_SETFL */
1298 if (tty_out
->old_tty
)
1299 while (emacs_set_tty (fileno (tty_out
->input
),
1300 tty_out
->old_tty
, 0) < 0 && errno
== EINTR
)
1303 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
1311 /* Set up the proper status flags for use of a pty. */
1316 /* I'm told that TOICREMOTE does not mean control chars
1317 "can't be sent" but rather that they don't have
1318 input-editing or signaling effects.
1319 That should be good, because we have other ways
1320 to do those things in Emacs.
1321 However, telnet mode seems not to work on 4.2.
1322 So TIOCREMOTE is turned off now. */
1324 /* Under hp-ux, if TIOCREMOTE is turned on, some calls
1325 will hang. In particular, the "timeout" feature (which
1326 causes a read to return if there is no data available)
1327 does this. Also it is known that telnet mode will hang
1328 in such a way that Emacs must be stopped (perhaps this
1329 is the same problem).
1331 If TIOCREMOTE is turned off, then there is a bug in
1332 hp-ux which sometimes loses data. Apparently the
1333 code which blocks the master process when the internal
1334 buffer fills up does not work. Other than this,
1335 though, everything else seems to work fine.
1337 Since the latter lossage is more benign, we may as well
1338 lose that way. -- cph */
1340 #if defined (UNIX98_PTYS)
1343 ioctl (fd
, FIONBIO
, &on
);
1348 #endif /* HAVE_PTYS */
1351 #include <sys/socket.h>
1353 #endif /* HAVE_SOCKETS */
1356 #ifndef HAVE_H_ERRNO
1359 #endif /* TRY_AGAIN */
1362 init_system_name (void)
1364 #ifndef HAVE_GETHOSTNAME
1367 Vsystem_name
= build_string (uts
.nodename
);
1368 #else /* HAVE_GETHOSTNAME */
1369 unsigned int hostname_size
= 256;
1370 char *hostname
= (char *) alloca (hostname_size
);
1372 /* Try to get the host name; if the buffer is too short, try
1373 again. Apparently, the only indication gethostname gives of
1374 whether the buffer was large enough is the presence or absence
1375 of a '\0' in the string. Eech. */
1378 gethostname (hostname
, hostname_size
- 1);
1379 hostname
[hostname_size
- 1] = '\0';
1381 /* Was the buffer large enough for the '\0'? */
1382 if (strlen (hostname
) < hostname_size
- 1)
1385 hostname_size
<<= 1;
1386 hostname
= (char *) alloca (hostname_size
);
1389 /* Turn the hostname into the official, fully-qualified hostname.
1390 Don't do this if we're going to dump; this can confuse system
1391 libraries on some machines and make the dumped emacs core dump. */
1394 #endif /* not CANNOT_DUMP */
1395 if (! strchr (hostname
, '.'))
1398 #ifdef HAVE_GETADDRINFO
1399 struct addrinfo
*res
;
1400 struct addrinfo hints
;
1403 memset (&hints
, 0, sizeof (hints
));
1404 hints
.ai_socktype
= SOCK_STREAM
;
1405 hints
.ai_flags
= AI_CANONNAME
;
1407 for (count
= 0;; count
++)
1409 if ((ret
= getaddrinfo (hostname
, NULL
, &hints
, &res
)) == 0
1410 || ret
!= EAI_AGAIN
)
1415 Fsleep_for (make_number (1), Qnil
);
1420 struct addrinfo
*it
= res
;
1423 char *fqdn
= it
->ai_canonname
;
1424 if (fqdn
&& strchr (fqdn
, '.')
1425 && strcmp (fqdn
, "localhost.localdomain") != 0)
1431 hostname
= alloca (strlen (it
->ai_canonname
) + 1);
1432 strcpy (hostname
, it
->ai_canonname
);
1436 #else /* !HAVE_GETADDRINFO */
1438 for (count
= 0;; count
++)
1444 hp
= gethostbyname (hostname
);
1446 if (! (hp
== 0 && h_errno
== TRY_AGAIN
))
1453 Fsleep_for (make_number (1), Qnil
);
1458 char *fqdn
= (char *) hp
->h_name
;
1460 if (!strchr (fqdn
, '.'))
1462 /* We still don't have a fully qualified domain name.
1463 Try to find one in the list of alternate names */
1464 char **alias
= hp
->h_aliases
;
1466 && (!strchr (*alias
, '.')
1467 || !strcmp (*alias
, "localhost.localdomain")))
1474 #endif /* !HAVE_GETADDRINFO */
1476 #endif /* HAVE_SOCKETS */
1477 Vsystem_name
= build_string (hostname
);
1478 #endif /* HAVE_GETHOSTNAME */
1481 for (p
= SDATA (Vsystem_name
); *p
; p
++)
1482 if (*p
== ' ' || *p
== '\t')
1487 /* POSIX signals support - DJB */
1488 /* Anyone with POSIX signals should have ANSI C declarations */
1490 sigset_t empty_mask
;
1495 sys_signal (int signal_number
, signal_handler_t action
)
1497 struct sigaction new_action
, old_action
;
1498 sigemptyset (&new_action
.sa_mask
);
1499 new_action
.sa_handler
= action
;
1500 new_action
.sa_flags
= 0;
1501 #if defined (SA_RESTART)
1502 /* Emacs mostly works better with restartable system services. If this
1503 flag exists, we probably want to turn it on here.
1504 However, on some systems this resets the timeout of `select'
1505 which means that `select' never finishes if it keeps getting signals.
1506 BROKEN_SA_RESTART is defined on those systems. */
1507 /* It's not clear why the comment above says "mostly works better". --Stef
1508 When SYNC_INPUT is set, we don't want SA_RESTART because we need to poll
1509 for pending input so we need long-running syscalls to be interrupted
1510 after a signal that sets the interrupt_input_pending flag. */
1511 /* Non-interactive keyboard input goes through stdio, where we always
1512 want restartable system calls. */
1513 # if defined (BROKEN_SA_RESTART) || defined (SYNC_INPUT)
1516 new_action
.sa_flags
= SA_RESTART
;
1518 sigaction (signal_number
, &new_action
, &old_action
);
1519 return (old_action
.sa_handler
);
1522 #endif /* WINDOWSNT */
1525 /* If we're compiling with GCC, we don't need this function, since it
1526 can be written as a macro. */
1528 sys_sigmask (int sig
)
1531 sigemptyset (&mask
);
1532 sigaddset (&mask
, sig
);
1537 /* I'd like to have these guys return pointers to the mask storage in here,
1538 but there'd be trouble if the code was saving multiple masks. I'll be
1539 safe and pass the structure. It normally won't be more than 2 bytes
1543 sys_sigblock (sigset_t new_mask
)
1546 pthread_sigmask (SIG_BLOCK
, &new_mask
, &old_mask
);
1551 sys_sigunblock (sigset_t new_mask
)
1554 pthread_sigmask (SIG_UNBLOCK
, &new_mask
, &old_mask
);
1559 sys_sigsetmask (sigset_t new_mask
)
1562 pthread_sigmask (SIG_SETMASK
, &new_mask
, &old_mask
);
1567 #if !defined HAVE_STRSIGNAL && !HAVE_DECL_SYS_SIGLIST
1568 static char *my_sys_siglist
[NSIG
];
1572 # define sys_siglist my_sys_siglist
1578 sigemptyset (&empty_mask
);
1580 #if !defined HAVE_STRSIGNAL && !HAVE_DECL_SYS_SIGLIST
1584 sys_siglist
[SIGABRT
] = "Aborted";
1587 sys_siglist
[SIGAIO
] = "LAN I/O interrupt";
1590 sys_siglist
[SIGALRM
] = "Alarm clock";
1593 sys_siglist
[SIGBUS
] = "Bus error";
1596 sys_siglist
[SIGCLD
] = "Child status changed";
1599 sys_siglist
[SIGCHLD
] = "Child status changed";
1602 sys_siglist
[SIGCONT
] = "Continued";
1605 sys_siglist
[SIGDANGER
] = "Swap space dangerously low";
1608 sys_siglist
[SIGDGNOTIFY
] = "Notification message in queue";
1611 sys_siglist
[SIGEMT
] = "Emulation trap";
1614 sys_siglist
[SIGFPE
] = "Arithmetic exception";
1617 sys_siglist
[SIGFREEZE
] = "SIGFREEZE";
1620 sys_siglist
[SIGGRANT
] = "Monitor mode granted";
1623 sys_siglist
[SIGHUP
] = "Hangup";
1626 sys_siglist
[SIGILL
] = "Illegal instruction";
1629 sys_siglist
[SIGINT
] = "Interrupt";
1632 sys_siglist
[SIGIO
] = "I/O possible";
1635 sys_siglist
[SIGIOINT
] = "I/O intervention required";
1638 sys_siglist
[SIGIOT
] = "IOT trap";
1641 sys_siglist
[SIGKILL
] = "Killed";
1644 sys_siglist
[SIGLOST
] = "Resource lost";
1647 sys_siglist
[SIGLWP
] = "SIGLWP";
1650 sys_siglist
[SIGMSG
] = "Monitor mode data available";
1653 sys_siglist
[SIGWIND
] = "SIGPHONE";
1656 sys_siglist
[SIGPIPE
] = "Broken pipe";
1659 sys_siglist
[SIGPOLL
] = "Pollable event occurred";
1662 sys_siglist
[SIGPROF
] = "Profiling timer expired";
1665 sys_siglist
[SIGPTY
] = "PTY I/O interrupt";
1668 sys_siglist
[SIGPWR
] = "Power-fail restart";
1671 sys_siglist
[SIGQUIT
] = "Quit";
1674 sys_siglist
[SIGRETRACT
] = "Need to relinquish monitor mode";
1677 sys_siglist
[SIGSAK
] = "Secure attention";
1680 sys_siglist
[SIGSEGV
] = "Segmentation violation";
1683 sys_siglist
[SIGSOUND
] = "Sound completed";
1686 sys_siglist
[SIGSTOP
] = "Stopped (signal)";
1689 sys_siglist
[SIGSTP
] = "Stopped (user)";
1692 sys_siglist
[SIGSYS
] = "Bad argument to system call";
1695 sys_siglist
[SIGTERM
] = "Terminated";
1698 sys_siglist
[SIGTHAW
] = "SIGTHAW";
1701 sys_siglist
[SIGTRAP
] = "Trace/breakpoint trap";
1704 sys_siglist
[SIGTSTP
] = "Stopped (user)";
1707 sys_siglist
[SIGTTIN
] = "Stopped (tty input)";
1710 sys_siglist
[SIGTTOU
] = "Stopped (tty output)";
1713 sys_siglist
[SIGURG
] = "Urgent I/O condition";
1716 sys_siglist
[SIGUSR1
] = "User defined signal 1";
1719 sys_siglist
[SIGUSR2
] = "User defined signal 2";
1722 sys_siglist
[SIGVTALRM
] = "Virtual timer expired";
1725 sys_siglist
[SIGWAITING
] = "Process's LWPs are blocked";
1728 sys_siglist
[SIGWINCH
] = "Window size changed";
1731 sys_siglist
[SIGWIND
] = "SIGWIND";
1734 sys_siglist
[SIGXCPU
] = "CPU time limit exceeded";
1737 sys_siglist
[SIGXFSZ
] = "File size limit exceeded";
1740 #endif /* !defined HAVE_STRSIGNAL && !defined HAVE_DECL_SYS_SIGLIST */
1749 /* Figure out how many bits the system's random number generator uses.
1750 `random' and `lrand48' are assumed to return 31 usable bits.
1751 BSD `rand' returns a 31 bit value but the low order bits are unusable;
1752 so we'll shift it and treat it like the 15-bit USG `rand'. */
1756 # define RAND_BITS 31
1757 # else /* !HAVE_RANDOM */
1758 # ifdef HAVE_LRAND48
1759 # define RAND_BITS 31
1760 # define random lrand48
1761 # else /* !HAVE_LRAND48 */
1762 # define RAND_BITS 15
1763 # if RAND_MAX == 32767
1764 # define random rand
1765 # else /* RAND_MAX != 32767 */
1766 # if RAND_MAX == 2147483647
1767 # define random() (rand () >> 16)
1768 # else /* RAND_MAX != 2147483647 */
1770 # define random rand
1772 # define random() (rand () >> 16)
1774 # endif /* RAND_MAX != 2147483647 */
1775 # endif /* RAND_MAX != 32767 */
1776 # endif /* !HAVE_LRAND48 */
1777 # endif /* !HAVE_RANDOM */
1778 #endif /* !RAND_BITS */
1781 seed_random (long int arg
)
1784 srandom ((unsigned int)arg
);
1786 # ifdef HAVE_LRAND48
1789 srand ((unsigned int)arg
);
1795 * Return a nonnegative random integer out of whatever we've got.
1796 * It contains enough bits to make a random (signed) Emacs fixnum.
1797 * This suffices even for a 64-bit architecture with a 15-bit rand.
1804 for (i
= 0; i
< (FIXNUM_BITS
+ RAND_BITS
- 1) / RAND_BITS
; i
++)
1805 val
= (random () ^ (val
<< RAND_BITS
)
1806 ^ (val
>> (BITS_PER_EMACS_INT
- RAND_BITS
)));
1807 val
^= val
>> (BITS_PER_EMACS_INT
- FIXNUM_BITS
);
1808 return val
& INTMASK
;
1811 #ifndef HAVE_STRERROR
1814 strerror (int errnum
)
1816 extern char *sys_errlist
[];
1817 extern int sys_nerr
;
1819 if (errnum
>= 0 && errnum
< sys_nerr
)
1820 return sys_errlist
[errnum
];
1821 return (char *) "Unknown error";
1823 #endif /* not WINDOWSNT */
1824 #endif /* ! HAVE_STRERROR */
1826 #ifndef HAVE_SNPRINTF
1827 /* Approximate snprintf as best we can on ancient hosts that lack it. */
1829 snprintf (char *buf
, size_t bufsize
, char const *format
, ...)
1831 ptrdiff_t size
= min (bufsize
, PTRDIFF_MAX
);
1832 ptrdiff_t nbytes
= size
- 1;
1837 va_start (ap
, format
);
1838 nbytes
= doprnt (buf
, size
, format
, 0, ap
);
1842 if (nbytes
== size
- 1)
1844 /* Calculate the length of the string that would have been created
1845 had the buffer been large enough. */
1846 char stackbuf
[4000];
1848 ptrdiff_t bsize
= sizeof stackbuf
;
1849 va_start (ap
, format
);
1850 nbytes
= evxprintf (&b
, &bsize
, stackbuf
, -1, format
, ap
);
1856 if (INT_MAX
< nbytes
)
1870 emacs_open (const char *path
, int oflag
, int mode
)
1872 register int rtnval
;
1874 while ((rtnval
= open (path
, oflag
, mode
)) == -1
1875 && (errno
== EINTR
))
1881 emacs_close (int fd
)
1884 register int rtnval
;
1886 while ((rtnval
= close (fd
)) == -1
1887 && (errno
== EINTR
))
1890 /* If close is interrupted SunOS 4.1 may or may not have closed the
1891 file descriptor. If it did the second close will fail with
1892 errno = EBADF. That means we have succeeded. */
1893 if (rtnval
== -1 && did_retry
&& errno
== EBADF
)
1899 /* Maximum number of bytes to read or write in a single system call.
1900 This works around a serious bug in Linux kernels before 2.6.16; see
1901 <https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=612839>.
1902 It's likely to work around similar bugs in other operating systems, so do it
1903 on all platforms. Round INT_MAX down to a page size, with the conservative
1904 assumption that page sizes are at most 2**18 bytes (any kernel with a
1905 page size larger than that shouldn't have the bug). */
1906 #ifndef MAX_RW_COUNT
1907 #define MAX_RW_COUNT (INT_MAX >> 18 << 18)
1910 /* Read from FILEDESC to a buffer BUF with size NBYTE, retrying if interrupted.
1911 Return the number of bytes read, which might be less than NBYTE.
1912 On error, set errno and return -1. */
1914 emacs_read (int fildes
, char *buf
, EMACS_INT nbyte
)
1916 register ssize_t rtnval
;
1918 /* There is no need to check against MAX_RW_COUNT, since no caller ever
1919 passes a size that large to emacs_read. */
1921 while ((rtnval
= read (fildes
, buf
, nbyte
)) == -1
1922 && (errno
== EINTR
))
1927 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if interrupted
1928 or if a partial write occurs. Return the number of bytes written, setting
1929 errno if this is less than NBYTE. */
1931 emacs_write (int fildes
, const char *buf
, EMACS_INT nbyte
)
1934 EMACS_INT bytes_written
;
1940 rtnval
= write (fildes
, buf
, min (nbyte
, MAX_RW_COUNT
));
1947 /* I originally used `QUIT' but that might causes files to
1948 be truncated if you hit C-g in the middle of it. --Stef */
1949 process_pending_signals ();
1959 bytes_written
+= rtnval
;
1962 return (bytes_written
);
1965 static struct allocator
const emacs_norealloc_allocator
=
1966 { xmalloc
, NULL
, xfree
, memory_full
};
1968 /* Get the symbolic link value of FILENAME. Return a pointer to a
1969 NUL-terminated string. If readlink fails, return NULL and set
1970 errno. If the value fits in INITIAL_BUF, return INITIAL_BUF.
1971 Otherwise, allocate memory and return a pointer to that memory. If
1972 memory allocation fails, diagnose and fail without returning. If
1973 successful, store the length of the symbolic link into *LINKLEN. */
1975 emacs_readlink (char const *filename
, char initial_buf
[READLINK_BUFSIZE
])
1977 return careadlinkat (AT_FDCWD
, filename
, initial_buf
, READLINK_BUFSIZE
,
1978 &emacs_norealloc_allocator
, careadlinkatcwd
);
1983 * All of the following are for USG.
1985 * On USG systems the system calls are INTERRUPTIBLE by signals
1986 * that the user program has elected to catch. Thus the system call
1987 * must be retried in these cases. To handle this without massive
1988 * changes in the source code, we remap the standard system call names
1989 * to names for our own functions in sysdep.c that do the system call
1990 * with retries. Actually, for portability reasons, it is good
1991 * programming practice, as this example shows, to limit all actual
1992 * system calls to a single occurrence in the source. Sure, this
1993 * adds an extra level of function call overhead but it is almost
1994 * always negligible. Fred Fish, Unisoft Systems Inc.
1998 * Warning, this function may not duplicate 4.2 action properly
1999 * under error conditions.
2005 /* In 4.1, param.h fails to define this. */
2006 #define MAXPATHLEN 1024
2010 getwd (char *pathname
)
2012 char *npath
, *spath
;
2013 extern char *getcwd (char *, size_t);
2015 BLOCK_INPUT
; /* getcwd uses malloc */
2016 spath
= npath
= getcwd ((char *) 0, MAXPATHLEN
);
2022 /* On Altos 3068, getcwd can return @hostname/dir, so discard
2023 up to first slash. Should be harmless on other systems. */
2024 while (*npath
&& *npath
!= '/')
2026 strcpy (pathname
, npath
);
2027 free (spath
); /* getcwd uses malloc */
2032 #endif /* HAVE_GETWD */
2035 * Emulate rename using unlink/link. Note that this is
2036 * only partially correct. Also, doesn't enforce restriction
2037 * that files be of same type (regular->regular, dir->dir, etc).
2043 rename (const char *from
, const char *to
)
2045 if (access (from
, 0) == 0)
2048 if (link (from
, to
) == 0)
2049 if (unlink (from
) == 0)
2058 #if defined (HPUX) && !defined (HAVE_PERROR)
2060 /* HPUX curses library references perror, but as far as we know
2061 it won't be called. Anyway this definition will do for now. */
2067 #endif /* HPUX and not HAVE_PERROR */
2070 * Gettimeofday. Simulate as much as possible. Only accurate
2071 * to nearest second. Emacs doesn't use tzp so ignore it for now.
2072 * Only needed when subprocesses are defined.
2075 #ifndef HAVE_GETTIMEOFDAY
2079 gettimeofday (struct timeval
*tp
, struct timezone
*tzp
)
2081 extern long time (long);
2083 tp
->tv_sec
= time ((long *)0);
2086 tzp
->tz_minuteswest
= -1;
2091 #endif /* !HAVE_GETTIMEOFDAY && HAVE_TIMEVAL */
2094 * This function will go away as soon as all the stubs fixed. (fnf)
2098 croak (char *badfunc
)
2100 printf ("%s not yet implemented\r\n", badfunc
);
2101 reset_all_sys_modes ();
2107 /* Directory routines for systems that don't have them. */
2109 #ifdef HAVE_DIRENT_H
2113 #if !defined (HAVE_CLOSEDIR)
2116 closedir (DIR *dirp
/* stream from opendir */)
2120 rtnval
= emacs_close (dirp
->dd_fd
);
2121 xfree ((char *) dirp
);
2125 #endif /* not HAVE_CLOSEDIR */
2126 #endif /* HAVE_DIRENT_H */
2130 set_file_times (const char *filename
, EMACS_TIME atime
, EMACS_TIME mtime
)
2133 struct timeval tv
[2];
2136 return utimes (filename
, tv
);
2137 #else /* not HAVE_UTIMES */
2139 utb
.actime
= EMACS_SECS (atime
);
2140 utb
.modtime
= EMACS_SECS (mtime
);
2141 return utime (filename
, &utb
);
2142 #endif /* not HAVE_UTIMES */
2145 /* mkdir and rmdir functions, for systems which don't have them. */
2149 * Written by Robert Rother, Mariah Corporation, August 1985.
2151 * If you want it, it's yours. All I ask in return is that if you
2152 * figure out how to do this in a Bourne Shell script you send me
2154 * sdcsvax!rmr or rmr@uscd
2156 * Severely hacked over by John Gilmore to make a 4.2BSD compatible
2157 * subroutine. 11Mar86; hoptoad!gnu
2159 * Modified by rmtodd@uokmax 6-28-87 -- when making an already existing dir,
2160 * subroutine didn't return EEXIST. It does now.
2167 mkdir (char *dpath
, int dmode
)
2169 int cpid
, status
, fd
;
2170 struct stat statbuf
;
2172 if (stat (dpath
, &statbuf
) == 0)
2174 errno
= EEXIST
; /* Stat worked, so it already exists */
2178 /* If stat fails for a reason other than non-existence, return error */
2179 if (errno
!= ENOENT
)
2182 synch_process_alive
= 1;
2183 switch (cpid
= fork ())
2186 case -1: /* Error in fork */
2187 return (-1); /* Errno is set already */
2189 case 0: /* Child process */
2191 * Cheap hack to set mode of new directory. Since this
2192 * child process is going away anyway, we zap its umask.
2193 * FIXME, this won't suffice to set SUID, SGID, etc. on this
2194 * directory. Does anybody care?
2196 status
= umask (0); /* Get current umask */
2197 status
= umask (status
| (0777 & ~dmode
)); /* Set for mkdir */
2198 fd
= emacs_open ("/dev/null", O_RDWR
, 0);
2205 execl ("/bin/mkdir", "mkdir", dpath
, (char *) 0);
2206 _exit (-1); /* Can't exec /bin/mkdir */
2208 default: /* Parent process */
2209 wait_for_termination (cpid
);
2212 if (synch_process_death
!= 0 || synch_process_retcode
!= 0
2213 || synch_process_termsig
!= 0)
2215 errno
= EIO
; /* We don't know why, but */
2216 return -1; /* /bin/mkdir failed */
2221 #endif /* not HAVE_MKDIR */
2227 int cpid
, status
, fd
;
2228 struct stat statbuf
;
2230 if (stat (dpath
, &statbuf
) != 0)
2232 /* Stat just set errno. We don't have to */
2236 synch_process_alive
= 1;
2237 switch (cpid
= fork ())
2240 case -1: /* Error in fork */
2241 return (-1); /* Errno is set already */
2243 case 0: /* Child process */
2244 fd
= emacs_open ("/dev/null", O_RDWR
, 0);
2251 execl ("/bin/rmdir", "rmdir", dpath
, (char *) 0);
2252 _exit (-1); /* Can't exec /bin/rmdir */
2254 default: /* Parent process */
2255 wait_for_termination (cpid
);
2258 if (synch_process_death
!= 0 || synch_process_retcode
!= 0
2259 || synch_process_termsig
!= 0)
2261 errno
= EIO
; /* We don't know why, but */
2262 return -1; /* /bin/rmdir failed */
2267 #endif /* !HAVE_RMDIR */
2270 #ifndef HAVE_STRSIGNAL
2272 strsignal (int code
)
2276 if (0 <= code
&& code
< NSIG
)
2278 /* Cast to suppress warning if the table has const char *. */
2279 signame
= (char *) sys_siglist
[code
];
2284 #endif /* HAVE_STRSIGNAL */
2287 /* For make-serial-process */
2289 serial_open (char *port
)
2293 fd
= emacs_open ((char*) port
,
2306 error ("Could not open %s: %s",
2307 port
, emacs_strerror (errno
));
2310 ioctl (fd
, TIOCEXCL
, (char *) 0);
2316 #if !defined (HAVE_CFMAKERAW)
2317 /* Workaround for targets which are missing cfmakeraw. */
2318 /* Pasted from man page. */
2320 cfmakeraw (struct termios
*termios_p
)
2322 termios_p
->c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
|INLCR
|IGNCR
|ICRNL
|IXON
);
2323 termios_p
->c_oflag
&= ~OPOST
;
2324 termios_p
->c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|ISIG
|IEXTEN
);
2325 termios_p
->c_cflag
&= ~(CSIZE
|PARENB
);
2326 termios_p
->c_cflag
|= CS8
;
2328 #endif /* !defined (HAVE_CFMAKERAW */
2330 #if !defined (HAVE_CFSETSPEED)
2331 /* Workaround for targets which are missing cfsetspeed. */
2333 cfsetspeed (struct termios
*termios_p
, speed_t vitesse
)
2335 return (cfsetispeed (termios_p
, vitesse
)
2336 + cfsetospeed (termios_p
, vitesse
));
2340 /* For serial-process-configure */
2342 serial_configure (struct Lisp_Process
*p
,
2343 Lisp_Object contact
)
2345 Lisp_Object childp2
= Qnil
;
2346 Lisp_Object tem
= Qnil
;
2347 struct termios attr
;
2349 char summary
[4] = "???"; /* This usually becomes "8N1". */
2351 childp2
= Fcopy_sequence (p
->childp
);
2353 /* Read port attributes and prepare default configuration. */
2354 err
= tcgetattr (p
->outfd
, &attr
);
2356 error ("tcgetattr() failed: %s", emacs_strerror (errno
));
2358 #if defined (CLOCAL)
2359 attr
.c_cflag
|= CLOCAL
;
2362 attr
.c_cflag
|= CREAD
;
2365 /* Configure speed. */
2366 if (!NILP (Fplist_member (contact
, QCspeed
)))
2367 tem
= Fplist_get (contact
, QCspeed
);
2369 tem
= Fplist_get (p
->childp
, QCspeed
);
2371 err
= cfsetspeed (&attr
, XINT (tem
));
2373 error ("cfsetspeed(%"pI
"d) failed: %s", XINT (tem
),
2374 emacs_strerror (errno
));
2375 childp2
= Fplist_put (childp2
, QCspeed
, tem
);
2377 /* Configure bytesize. */
2378 if (!NILP (Fplist_member (contact
, QCbytesize
)))
2379 tem
= Fplist_get (contact
, QCbytesize
);
2381 tem
= Fplist_get (p
->childp
, QCbytesize
);
2383 tem
= make_number (8);
2385 if (XINT (tem
) != 7 && XINT (tem
) != 8)
2386 error (":bytesize must be nil (8), 7, or 8");
2387 summary
[0] = XINT (tem
) + '0';
2388 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2389 attr
.c_cflag
&= ~CSIZE
;
2390 attr
.c_cflag
|= ((XINT (tem
) == 7) ? CS7
: CS8
);
2392 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2393 if (XINT (tem
) != 8)
2394 error ("Bytesize cannot be changed");
2396 childp2
= Fplist_put (childp2
, QCbytesize
, tem
);
2398 /* Configure parity. */
2399 if (!NILP (Fplist_member (contact
, QCparity
)))
2400 tem
= Fplist_get (contact
, QCparity
);
2402 tem
= Fplist_get (p
->childp
, QCparity
);
2403 if (!NILP (tem
) && !EQ (tem
, Qeven
) && !EQ (tem
, Qodd
))
2404 error (":parity must be nil (no parity), `even', or `odd'");
2405 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2406 attr
.c_cflag
&= ~(PARENB
| PARODD
);
2407 attr
.c_iflag
&= ~(IGNPAR
| INPCK
);
2412 else if (EQ (tem
, Qeven
))
2415 attr
.c_cflag
|= PARENB
;
2416 attr
.c_iflag
|= (IGNPAR
| INPCK
);
2418 else if (EQ (tem
, Qodd
))
2421 attr
.c_cflag
|= (PARENB
| PARODD
);
2422 attr
.c_iflag
|= (IGNPAR
| INPCK
);
2425 /* Don't error on no parity, which should be set by cfmakeraw. */
2427 error ("Parity cannot be configured");
2429 childp2
= Fplist_put (childp2
, QCparity
, tem
);
2431 /* Configure stopbits. */
2432 if (!NILP (Fplist_member (contact
, QCstopbits
)))
2433 tem
= Fplist_get (contact
, QCstopbits
);
2435 tem
= Fplist_get (p
->childp
, QCstopbits
);
2437 tem
= make_number (1);
2439 if (XINT (tem
) != 1 && XINT (tem
) != 2)
2440 error (":stopbits must be nil (1 stopbit), 1, or 2");
2441 summary
[2] = XINT (tem
) + '0';
2442 #if defined (CSTOPB)
2443 attr
.c_cflag
&= ~CSTOPB
;
2444 if (XINT (tem
) == 2)
2445 attr
.c_cflag
|= CSTOPB
;
2447 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2448 if (XINT (tem
) != 1)
2449 error ("Stopbits cannot be configured");
2451 childp2
= Fplist_put (childp2
, QCstopbits
, tem
);
2453 /* Configure flowcontrol. */
2454 if (!NILP (Fplist_member (contact
, QCflowcontrol
)))
2455 tem
= Fplist_get (contact
, QCflowcontrol
);
2457 tem
= Fplist_get (p
->childp
, QCflowcontrol
);
2458 if (!NILP (tem
) && !EQ (tem
, Qhw
) && !EQ (tem
, Qsw
))
2459 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
2460 #if defined (CRTSCTS)
2461 attr
.c_cflag
&= ~CRTSCTS
;
2463 #if defined (CNEW_RTSCTS)
2464 attr
.c_cflag
&= ~CNEW_RTSCTS
;
2466 #if defined (IXON) && defined (IXOFF)
2467 attr
.c_iflag
&= ~(IXON
| IXOFF
);
2471 /* Already configured. */
2473 else if (EQ (tem
, Qhw
))
2475 #if defined (CRTSCTS)
2476 attr
.c_cflag
|= CRTSCTS
;
2477 #elif defined (CNEW_RTSCTS)
2478 attr
.c_cflag
|= CNEW_RTSCTS
;
2480 error ("Hardware flowcontrol (RTS/CTS) not supported");
2483 else if (EQ (tem
, Qsw
))
2485 #if defined (IXON) && defined (IXOFF)
2486 attr
.c_iflag
|= (IXON
| IXOFF
);
2488 error ("Software flowcontrol (XON/XOFF) not supported");
2491 childp2
= Fplist_put (childp2
, QCflowcontrol
, tem
);
2493 /* Activate configuration. */
2494 err
= tcsetattr (p
->outfd
, TCSANOW
, &attr
);
2496 error ("tcsetattr() failed: %s", emacs_strerror (errno
));
2498 childp2
= Fplist_put (childp2
, QCsummary
, build_string (summary
));
2499 p
->childp
= childp2
;
2502 #endif /* not DOS_NT */
2504 /* System depended enumeration of and access to system processes a-la ps(1). */
2508 /* Process enumeration and access via /proc. */
2511 list_system_processes (void)
2513 Lisp_Object procdir
, match
, proclist
, next
;
2514 struct gcpro gcpro1
, gcpro2
;
2515 register Lisp_Object tail
;
2517 GCPRO2 (procdir
, match
);
2518 /* For every process on the system, there's a directory in the
2519 "/proc" pseudo-directory whose name is the numeric ID of that
2521 procdir
= build_string ("/proc");
2522 match
= build_string ("[0-9]+");
2523 proclist
= directory_files_internal (procdir
, Qnil
, match
, Qt
, 0, Qnil
);
2525 /* `proclist' gives process IDs as strings. Destructively convert
2526 each string into a number. */
2527 for (tail
= proclist
; CONSP (tail
); tail
= next
)
2530 XSETCAR (tail
, Fstring_to_number (XCAR (tail
), Qnil
));
2534 /* directory_files_internal returns the files in reverse order; undo
2536 proclist
= Fnreverse (proclist
);
2540 #elif defined BSD_SYSTEM
2543 list_system_processes (void)
2546 int mib
[] = {CTL_KERN
, KERN_PROC
, KERN_PROC_ALL
};
2548 int mib
[] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PROC
};
2551 struct kinfo_proc
*procs
;
2554 struct gcpro gcpro1
;
2555 Lisp_Object proclist
= Qnil
;
2557 if (sysctl (mib
, 3, NULL
, &len
, NULL
, 0) != 0)
2560 procs
= xmalloc (len
);
2561 if (sysctl (mib
, 3, procs
, &len
, NULL
, 0) != 0)
2568 len
/= sizeof (struct kinfo_proc
);
2569 for (i
= 0; i
< len
; i
++)
2572 proclist
= Fcons (make_fixnum_or_float (procs
[i
].kp_proc
.p_pid
), proclist
);
2574 proclist
= Fcons (make_fixnum_or_float (procs
[i
].ki_pid
), proclist
);
2584 /* The WINDOWSNT implementation is in w32.c.
2585 The MSDOS implementation is in dosfns.c. */
2586 #elif !defined (WINDOWSNT) && !defined (MSDOS)
2589 list_system_processes (void)
2594 #endif /* !defined (WINDOWSNT) */
2598 time_from_jiffies (unsigned long long tval
, long hz
,
2599 time_t *sec
, unsigned *usec
)
2601 unsigned long long ullsec
;
2605 tval
-= ullsec
* hz
;
2606 /* Careful: if HZ > 1 million, then integer division by it yields zero. */
2608 *usec
= tval
* 1000000 / hz
;
2610 *usec
= tval
/ (hz
/ 1000000);
2614 ltime_from_jiffies (unsigned long long tval
, long hz
)
2619 time_from_jiffies (tval
, hz
, &sec
, &usec
);
2621 return list3 (make_number ((sec
>> 16) & 0xffff),
2622 make_number (sec
& 0xffff),
2623 make_number (usec
));
2627 get_up_time (time_t *sec
, unsigned *usec
)
2634 fup
= fopen ("/proc/uptime", "r");
2638 double uptime
, idletime
;
2640 /* The numbers in /proc/uptime use C-locale decimal point, but
2641 we already set ourselves to the C locale (see `fixup_locale'
2643 if (2 <= fscanf (fup
, "%lf %lf", &uptime
, &idletime
))
2646 *usec
= (uptime
- *sec
) * 1000000;
2653 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
2654 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
2657 procfs_ttyname (int rdev
)
2660 char name
[PATH_MAX
];
2663 fdev
= fopen ("/proc/tty/drivers", "r");
2668 unsigned long minor_beg
, minor_end
;
2669 char minor
[25]; /* 2 32-bit numbers + dash */
2672 while (!feof (fdev
) && !ferror (fdev
))
2674 if (3 <= fscanf (fdev
, "%*s %s %u %s %*s\n", name
, &major
, minor
)
2675 && major
== MAJOR (rdev
))
2677 minor_beg
= strtoul (minor
, &endp
, 0);
2679 minor_end
= minor_beg
;
2680 else if (*endp
== '-')
2681 minor_end
= strtoul (endp
+ 1, &endp
, 0);
2685 if (MINOR (rdev
) >= minor_beg
&& MINOR (rdev
) <= minor_end
)
2687 sprintf (name
+ strlen (name
), "%u", MINOR (rdev
));
2695 return build_string (name
);
2698 static unsigned long
2699 procfs_get_total_memory (void)
2702 unsigned long retval
= 2 * 1024 * 1024; /* default: 2GB */
2705 fmem
= fopen ("/proc/meminfo", "r");
2709 unsigned long entry_value
;
2710 char entry_name
[20]; /* the longest I saw is 13+1 */
2712 while (!feof (fmem
) && !ferror (fmem
))
2714 if (2 <= fscanf (fmem
, "%s %lu kB\n", entry_name
, &entry_value
)
2715 && strcmp (entry_name
, "MemTotal:") == 0)
2717 retval
= entry_value
;
2728 system_process_attributes (Lisp_Object pid
)
2730 char procfn
[PATH_MAX
], fn
[PATH_MAX
];
2734 long clocks_per_sec
;
2736 char procbuf
[1025], *p
, *q
;
2739 const char *cmd
= NULL
;
2740 char *cmdline
= NULL
;
2741 ptrdiff_t cmdsize
= 0, cmdline_size
;
2743 int proc_id
, ppid
, uid
, gid
, pgrp
, sess
, tty
, tpgid
, thcount
;
2744 unsigned long long u_time
, s_time
, cutime
, cstime
, start
;
2745 long priority
, niceness
, rss
;
2746 unsigned long minflt
, majflt
, cminflt
, cmajflt
, vsize
;
2749 EMACS_TIME tnow
, tstart
, tboot
, telapsed
;
2751 Lisp_Object attrs
= Qnil
;
2752 Lisp_Object cmd_str
, decoded_cmd
, tem
;
2753 struct gcpro gcpro1
, gcpro2
;
2754 EMACS_INT uid_eint
, gid_eint
;
2756 CHECK_NUMBER_OR_FLOAT (pid
);
2757 proc_id
= FLOATP (pid
) ? XFLOAT_DATA (pid
) : XINT (pid
);
2758 sprintf (procfn
, "/proc/%u", proc_id
);
2759 if (stat (procfn
, &st
) < 0)
2762 GCPRO2 (attrs
, decoded_cmd
);
2766 /* Use of EMACS_INT stops GCC whining about limited range of data type. */
2768 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid_eint
)), attrs
);
2770 pw
= getpwuid (uid
);
2773 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
2777 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid_eint
)), attrs
);
2779 gr
= getgrgid (gid
);
2782 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
2784 strcpy (fn
, procfn
);
2785 procfn_end
= fn
+ strlen (fn
);
2786 strcpy (procfn_end
, "/stat");
2787 fd
= emacs_open (fn
, O_RDONLY
, 0);
2788 if (fd
>= 0 && (nread
= emacs_read (fd
, procbuf
, sizeof (procbuf
) - 1)) > 0)
2790 procbuf
[nread
] = '\0';
2793 p
= strchr (p
, '(');
2796 q
= strrchr (p
+ 1, ')');
2811 /* Command name is encoded in locale-coding-system; decode it. */
2812 cmd_str
= make_unibyte_string (cmd
, cmdsize
);
2813 decoded_cmd
= code_convert_string_norecord (cmd_str
,
2814 Vlocale_coding_system
, 0);
2815 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
2819 EMACS_INT ppid_eint
, pgrp_eint
, sess_eint
, tpgid_eint
, thcount_eint
;
2821 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt utime stime cutime cstime priority nice thcount . start vsize rss */
2822 sscanf (p
, "%c %d %d %d %d %d %*u %lu %lu %lu %lu %Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld",
2823 &c
, &ppid
, &pgrp
, &sess
, &tty
, &tpgid
,
2824 &minflt
, &cminflt
, &majflt
, &cmajflt
,
2825 &u_time
, &s_time
, &cutime
, &cstime
,
2826 &priority
, &niceness
, &thcount
, &start
, &vsize
, &rss
);
2831 state_str
[1] = '\0';
2832 tem
= build_string (state_str
);
2833 attrs
= Fcons (Fcons (Qstate
, tem
), attrs
);
2835 /* Stops GCC whining about limited range of data type. */
2840 thcount_eint
= thcount
;
2841 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (ppid_eint
)), attrs
);
2842 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (pgrp_eint
)), attrs
);
2843 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (sess_eint
)), attrs
);
2844 attrs
= Fcons (Fcons (Qttname
, procfs_ttyname (tty
)), attrs
);
2845 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (tpgid_eint
)), attrs
);
2846 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (minflt
)), attrs
);
2847 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (majflt
)), attrs
);
2848 attrs
= Fcons (Fcons (Qcminflt
, make_fixnum_or_float (cminflt
)), attrs
);
2849 attrs
= Fcons (Fcons (Qcmajflt
, make_fixnum_or_float (cmajflt
)), attrs
);
2850 clocks_per_sec
= sysconf (_SC_CLK_TCK
);
2851 if (clocks_per_sec
< 0)
2852 clocks_per_sec
= 100;
2853 attrs
= Fcons (Fcons (Qutime
,
2854 ltime_from_jiffies (u_time
, clocks_per_sec
)),
2856 attrs
= Fcons (Fcons (Qstime
,
2857 ltime_from_jiffies (s_time
, clocks_per_sec
)),
2859 attrs
= Fcons (Fcons (Qtime
,
2860 ltime_from_jiffies (s_time
+ u_time
,
2863 attrs
= Fcons (Fcons (Qcutime
,
2864 ltime_from_jiffies (cutime
, clocks_per_sec
)),
2866 attrs
= Fcons (Fcons (Qcstime
,
2867 ltime_from_jiffies (cstime
, clocks_per_sec
)),
2869 attrs
= Fcons (Fcons (Qctime
,
2870 ltime_from_jiffies (cstime
+cutime
, clocks_per_sec
)),
2872 attrs
= Fcons (Fcons (Qpri
, make_number (priority
)), attrs
);
2873 attrs
= Fcons (Fcons (Qnice
, make_number (niceness
)), attrs
);
2874 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (thcount_eint
)), attrs
);
2875 EMACS_GET_TIME (tnow
);
2876 get_up_time (&sec
, &usec
);
2877 EMACS_SET_SECS (telapsed
, sec
);
2878 EMACS_SET_USECS (telapsed
, usec
);
2879 EMACS_SUB_TIME (tboot
, tnow
, telapsed
);
2880 time_from_jiffies (start
, clocks_per_sec
, &sec
, &usec
);
2881 EMACS_SET_SECS (tstart
, sec
);
2882 EMACS_SET_USECS (tstart
, usec
);
2883 EMACS_ADD_TIME (tstart
, tboot
, tstart
);
2884 attrs
= Fcons (Fcons (Qstart
,
2886 ((EMACS_SECS (tstart
) >> 16) & 0xffff),
2888 (EMACS_SECS (tstart
) & 0xffff),
2890 (EMACS_USECS (tstart
)))),
2892 attrs
= Fcons (Fcons (Qvsize
, make_fixnum_or_float (vsize
/1024)), attrs
);
2893 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (4*rss
)), attrs
);
2894 EMACS_SUB_TIME (telapsed
, tnow
, tstart
);
2895 attrs
= Fcons (Fcons (Qetime
,
2897 ((EMACS_SECS (telapsed
) >> 16) & 0xffff),
2899 (EMACS_SECS (telapsed
) & 0xffff),
2901 (EMACS_USECS (telapsed
)))),
2903 time_from_jiffies (u_time
+ s_time
, clocks_per_sec
, &sec
, &usec
);
2904 pcpu
= (sec
+ usec
/ 1000000.0) / (EMACS_SECS (telapsed
) + EMACS_USECS (telapsed
) / 1000000.0);
2907 attrs
= Fcons (Fcons (Qpcpu
, make_float (100 * pcpu
)), attrs
);
2908 pmem
= 4.0 * 100 * rss
/ procfs_get_total_memory ();
2911 attrs
= Fcons (Fcons (Qpmem
, make_float (pmem
)), attrs
);
2918 strcpy (procfn_end
, "/cmdline");
2919 fd
= emacs_open (fn
, O_RDONLY
, 0);
2923 for (cmdline_size
= 0; cmdline_size
< STRING_BYTES_BOUND
; cmdline_size
++)
2925 if (emacs_read (fd
, &ch
, 1) != 1)
2928 if (isspace (c
) || c
== '\\')
2929 cmdline_size
++; /* for later quoting, see below */
2933 cmdline
= xmalloc (cmdline_size
+ 1);
2934 lseek (fd
, 0L, SEEK_SET
);
2936 if ((nread
= read (fd
, cmdline
, cmdline_size
)) >= 0)
2937 cmdline
[nread
++] = '\0';
2940 /* Assigning zero to `nread' makes us skip the following
2941 two loops, assign zero to cmdline_size, and enter the
2942 following `if' clause that handles unknown command
2946 /* We don't want trailing null characters. */
2947 for (p
= cmdline
+ nread
; p
> cmdline
+ 1 && !p
[-1]; p
--)
2949 for (p
= cmdline
; p
< cmdline
+ nread
; p
++)
2951 /* Escape-quote whitespace and backslashes. */
2952 if (isspace (*p
) || *p
== '\\')
2954 memmove (p
+ 1, p
, nread
- (p
- cmdline
));
2958 else if (*p
== '\0')
2961 cmdline_size
= nread
;
2968 cmdsize
= strlen (cmd
);
2969 cmdline_size
= cmdsize
+ 2;
2970 cmdline
= xmalloc (cmdline_size
+ 1);
2971 strcpy (cmdline
, "[");
2972 strcat (strncat (cmdline
, cmd
, cmdsize
), "]");
2975 /* Command line is encoded in locale-coding-system; decode it. */
2976 cmd_str
= make_unibyte_string (cmdline
, cmdline_size
);
2977 decoded_cmd
= code_convert_string_norecord (cmd_str
,
2978 Vlocale_coding_system
, 0);
2980 attrs
= Fcons (Fcons (Qargs
, decoded_cmd
), attrs
);
2987 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
2989 /* The <procfs.h> header does not like to be included if _LP64 is defined and
2990 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
2991 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
2992 #define PROCFS_FILE_OFFSET_BITS_HACK 1
2993 #undef _FILE_OFFSET_BITS
2995 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3000 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3001 #define _FILE_OFFSET_BITS 64
3002 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3004 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3007 system_process_attributes (Lisp_Object pid
)
3009 char procfn
[PATH_MAX
], fn
[PATH_MAX
];
3014 struct psinfo pinfo
;
3017 int proc_id
, uid
, gid
;
3018 Lisp_Object attrs
= Qnil
;
3019 Lisp_Object decoded_cmd
, tem
;
3020 struct gcpro gcpro1
, gcpro2
;
3021 EMACS_INT uid_eint
, gid_eint
;
3023 CHECK_NUMBER_OR_FLOAT (pid
);
3024 proc_id
= FLOATP (pid
) ? XFLOAT_DATA (pid
) : XINT (pid
);
3025 sprintf (procfn
, "/proc/%u", proc_id
);
3026 if (stat (procfn
, &st
) < 0)
3029 GCPRO2 (attrs
, decoded_cmd
);
3033 /* Use of EMACS_INT stops GCC whining about limited range of data type. */
3035 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid_eint
)), attrs
);
3037 pw
= getpwuid (uid
);
3040 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3044 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid_eint
)), attrs
);
3046 gr
= getgrgid (gid
);
3049 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3051 strcpy (fn
, procfn
);
3052 procfn_end
= fn
+ strlen (fn
);
3053 strcpy (procfn_end
, "/psinfo");
3054 fd
= emacs_open (fn
, O_RDONLY
, 0);
3056 && (nread
= read (fd
, (char*)&pinfo
, sizeof (struct psinfo
)) > 0))
3058 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (pinfo
.pr_ppid
)), attrs
);
3059 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (pinfo
.pr_pgid
)), attrs
);
3060 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (pinfo
.pr_sid
)), attrs
);
3064 state_str
[0] = pinfo
.pr_lwp
.pr_sname
;
3065 state_str
[1] = '\0';
3066 tem
= build_string (state_str
);
3067 attrs
= Fcons (Fcons (Qstate
, tem
), attrs
);
3070 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3071 need to get a string from it. */
3073 /* FIXME: missing: Qtpgid */
3085 Are they available? */
3087 attrs
= Fcons (Fcons (Qtime
,
3088 list3 (make_number (pinfo
.pr_time
.tv_sec
>> 16),
3089 make_number (pinfo
.pr_time
.tv_sec
& 0xffff),
3090 make_number (pinfo
.pr_time
.tv_nsec
))),
3093 attrs
= Fcons (Fcons (Qctime
,
3094 list3 (make_number (pinfo
.pr_ctime
.tv_sec
>> 16),
3095 make_number (pinfo
.pr_ctime
.tv_sec
& 0xffff),
3096 make_number (pinfo
.pr_ctime
.tv_nsec
))),
3099 attrs
= Fcons (Fcons (Qpri
, make_number (pinfo
.pr_lwp
.pr_pri
)), attrs
);
3100 attrs
= Fcons (Fcons (Qnice
, make_number (pinfo
.pr_lwp
.pr_nice
)), attrs
);
3101 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (pinfo
.pr_nlwp
)), attrs
);
3103 attrs
= Fcons (Fcons (Qstart
,
3104 list3 (make_number (pinfo
.pr_start
.tv_sec
>> 16),
3105 make_number (pinfo
.pr_start
.tv_sec
& 0xffff),
3106 make_number (pinfo
.pr_start
.tv_nsec
))),
3108 attrs
= Fcons (Fcons (Qvsize
, make_fixnum_or_float (pinfo
.pr_size
)), attrs
);
3109 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (pinfo
.pr_rssize
)), attrs
);
3111 /* pr_pctcpu and pr_pctmem are encoded as a fixed point 16 bit number in [0 ... 1]. */
3112 attrs
= Fcons (Fcons (Qpcpu
, (pinfo
.pr_pctcpu
* 100.0) / (double)0x8000), attrs
);
3113 attrs
= Fcons (Fcons (Qpmem
, (pinfo
.pr_pctmem
* 100.0) / (double)0x8000), attrs
);
3116 = code_convert_string_norecord (make_unibyte_string (pinfo
.pr_fname
,
3117 strlen (pinfo
.pr_fname
)),
3118 Vlocale_coding_system
, 0);
3119 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
3121 = code_convert_string_norecord (make_unibyte_string (pinfo
.pr_psargs
,
3122 strlen (pinfo
.pr_psargs
)),
3123 Vlocale_coding_system
, 0);
3124 attrs
= Fcons (Fcons (Qargs
, decoded_cmd
), attrs
);
3134 #elif defined __FreeBSD__
3137 system_process_attributes (Lisp_Object pid
)
3140 int pagesize
= getpagesize ();
3147 char args
[MAXPATHLEN
];
3150 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PID
};
3151 struct kinfo_proc proc
;
3152 size_t proclen
= sizeof proc
;
3154 struct gcpro gcpro1
, gcpro2
;
3155 Lisp_Object attrs
= Qnil
;
3156 Lisp_Object decoded_comm
;
3158 CHECK_NUMBER_OR_FLOAT (pid
);
3159 proc_id
= FLOATP (pid
) ? XFLOAT_DATA (pid
) : XINT (pid
);
3162 if (sysctl (mib
, 4, &proc
, &proclen
, NULL
, 0) != 0)
3165 GCPRO2 (attrs
, decoded_comm
);
3167 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (proc
.ki_uid
)), attrs
);
3170 pw
= getpwuid (proc
.ki_uid
);
3173 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3175 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (proc
.ki_svgid
)), attrs
);
3178 gr
= getgrgid (proc
.ki_svgid
);
3181 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3183 decoded_comm
= code_convert_string_norecord
3184 (make_unibyte_string (proc
.ki_comm
, strlen (proc
.ki_comm
)),
3185 Vlocale_coding_system
, 0);
3187 attrs
= Fcons (Fcons (Qcomm
, decoded_comm
), attrs
);
3189 char state
[2] = {'\0', '\0'};
3190 switch (proc
.ki_stat
)
3212 attrs
= Fcons (Fcons (Qstate
, build_string (state
)), attrs
);
3215 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (proc
.ki_ppid
)), attrs
);
3216 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (proc
.ki_pgid
)), attrs
);
3217 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (proc
.ki_sid
)), attrs
);
3220 ttyname
= proc
.ki_tdev
== NODEV
? NULL
: devname (proc
.ki_tdev
, S_IFCHR
);
3223 attrs
= Fcons (Fcons (Qtty
, build_string (ttyname
)), attrs
);
3225 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (proc
.ki_tpgid
)), attrs
);
3226 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (proc
.ki_rusage
.ru_minflt
)), attrs
);
3227 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (proc
.ki_rusage
.ru_majflt
)), attrs
);
3228 attrs
= Fcons (Fcons (Qcminflt
, make_number (proc
.ki_rusage_ch
.ru_minflt
)), attrs
);
3229 attrs
= Fcons (Fcons (Qcmajflt
, make_number (proc
.ki_rusage_ch
.ru_majflt
)), attrs
);
3231 #define TIMELIST(ts) \
3232 list3 (make_number (EMACS_SECS (ts) >> 16 & 0xffff), \
3233 make_number (EMACS_SECS (ts) & 0xffff), \
3234 make_number (EMACS_USECS (ts)))
3236 attrs
= Fcons (Fcons (Qutime
, TIMELIST (proc
.ki_rusage
.ru_utime
)), attrs
);
3237 attrs
= Fcons (Fcons (Qstime
, TIMELIST (proc
.ki_rusage
.ru_stime
)), attrs
);
3238 EMACS_ADD_TIME (t
, proc
.ki_rusage
.ru_utime
, proc
.ki_rusage
.ru_stime
);
3239 attrs
= Fcons (Fcons (Qtime
, TIMELIST (t
)), attrs
);
3241 attrs
= Fcons (Fcons (Qcutime
, TIMELIST (proc
.ki_rusage_ch
.ru_utime
)), attrs
);
3242 attrs
= Fcons (Fcons (Qcstime
, TIMELIST (proc
.ki_rusage_ch
.ru_utime
)), attrs
);
3243 EMACS_ADD_TIME (t
, proc
.ki_rusage_ch
.ru_utime
, proc
.ki_rusage_ch
.ru_stime
);
3244 attrs
= Fcons (Fcons (Qctime
, TIMELIST (t
)), attrs
);
3246 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (proc
.ki_numthreads
)),
3248 attrs
= Fcons (Fcons (Qpri
, make_number (proc
.ki_pri
.pri_native
)), attrs
);
3249 attrs
= Fcons (Fcons (Qnice
, make_number (proc
.ki_nice
)), attrs
);
3250 attrs
= Fcons (Fcons (Qstart
, TIMELIST (proc
.ki_start
)), attrs
);
3251 attrs
= Fcons (Fcons (Qvsize
, make_number (proc
.ki_size
>> 10)), attrs
);
3252 attrs
= Fcons (Fcons (Qrss
, make_number (proc
.ki_rssize
* pagesize
>> 10)),
3255 EMACS_GET_TIME (now
);
3256 EMACS_SUB_TIME (t
, now
, proc
.ki_start
);
3257 attrs
= Fcons (Fcons (Qetime
, TIMELIST (t
)), attrs
);
3261 len
= sizeof fscale
;
3262 if (sysctlbyname ("kern.fscale", &fscale
, &len
, NULL
, 0) == 0)
3267 if (sysctlbyname ("kern.ccpu", &ccpu
, &len
, NULL
, 0) == 0)
3269 pcpu
= (100.0 * proc
.ki_pctcpu
/ fscale
3270 / (1 - exp (proc
.ki_swtime
* log ((double) ccpu
/ fscale
))));
3271 attrs
= Fcons (Fcons (Qpcpu
, make_fixnum_or_float (pcpu
)), attrs
);
3275 len
= sizeof npages
;
3276 if (sysctlbyname ("hw.availpages", &npages
, &len
, NULL
, 0) == 0)
3278 double pmem
= (proc
.ki_flag
& P_INMEM
3279 ? 100.0 * proc
.ki_rssize
/ npages
3281 attrs
= Fcons (Fcons (Qpmem
, make_fixnum_or_float (pmem
)), attrs
);
3284 mib
[2] = KERN_PROC_ARGS
;
3286 if (sysctl (mib
, 4, args
, &len
, NULL
, 0) == 0)
3289 for (i
= 0; i
< len
; i
++)
3291 if (! args
[i
] && i
< len
- 1)
3296 (code_convert_string_norecord
3297 (make_unibyte_string (args
, strlen (args
)),
3298 Vlocale_coding_system
, 0));
3300 attrs
= Fcons (Fcons (Qargs
, decoded_comm
), attrs
);
3307 /* The WINDOWSNT implementation is in w32.c.
3308 The MSDOS implementation is in dosfns.c. */
3309 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3312 system_process_attributes (Lisp_Object pid
)
3317 #endif /* !defined (WINDOWSNT) */