Describe buffer-face-mode properly.
[emacs.git] / src / process.c
blob2471ee187bf0dd5e94228b450149dc4a7626461b
1 /* Asynchronous subprocess control for GNU Emacs.
2 Copyright (C) 1985, 1986, 1987, 1988, 1993, 1994, 1995,
3 1996, 1998, 1999, 2001, 2002, 2003, 2004,
4 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
23 #include <signal.h>
25 /* This file is split into two parts by the following preprocessor
26 conditional. The 'then' clause contains all of the support for
27 asynchronous subprocesses. The 'else' clause contains stub
28 versions of some of the asynchronous subprocess routines that are
29 often called elsewhere in Emacs, so we don't have to #ifdef the
30 sections that call them. */
33 #ifdef subprocesses
35 #include <stdio.h>
36 #include <errno.h>
37 #include <setjmp.h>
38 #include <sys/types.h> /* some typedefs are used in sys/file.h */
39 #include <sys/file.h>
40 #include <sys/stat.h>
41 #ifdef HAVE_INTTYPES_H
42 #include <inttypes.h>
43 #endif
44 #ifdef STDC_HEADERS
45 #include <stdlib.h>
46 #endif
48 #ifdef HAVE_UNISTD_H
49 #include <unistd.h>
50 #endif
51 #include <fcntl.h>
53 #ifdef HAVE_SOCKETS /* TCP connection support, if kernel can do it */
54 #include <sys/socket.h>
55 #include <netdb.h>
56 #include <netinet/in.h>
57 #include <arpa/inet.h>
59 /* Are local (unix) sockets supported? */
60 #if defined (HAVE_SYS_UN_H)
61 #if !defined (AF_LOCAL) && defined (AF_UNIX)
62 #define AF_LOCAL AF_UNIX
63 #endif
64 #ifdef AF_LOCAL
65 #define HAVE_LOCAL_SOCKETS
66 #include <sys/un.h>
67 #endif
68 #endif
69 #endif /* HAVE_SOCKETS */
71 #if defined(BSD_SYSTEM)
72 #include <sys/ioctl.h>
73 #if !defined (O_NDELAY) && defined (HAVE_PTYS) && !defined(USG5)
74 #include <fcntl.h>
75 #endif /* HAVE_PTYS and no O_NDELAY */
76 #endif /* BSD_SYSTEM */
78 #ifdef NEED_BSDTTY
79 #include <bsdtty.h>
80 #endif
82 /* Can we use SIOCGIFCONF and/or SIOCGIFADDR */
83 #ifdef HAVE_SOCKETS
84 #if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_NET_IF_H)
85 /* sys/ioctl.h may have been included already */
86 #ifndef SIOCGIFADDR
87 #include <sys/ioctl.h>
88 #endif
89 #include <net/if.h>
90 #endif
91 #endif
93 #ifdef HAVE_SYS_WAIT
94 #include <sys/wait.h>
95 #endif
97 #ifdef HAVE_RES_INIT
98 #include <netinet/in.h>
99 #include <arpa/nameser.h>
100 #include <resolv.h>
101 #endif
103 #include "lisp.h"
104 #include "systime.h"
105 #include "systty.h"
107 #include "window.h"
108 #include "buffer.h"
109 #include "character.h"
110 #include "coding.h"
111 #include "process.h"
112 #include "frame.h"
113 #include "termhooks.h"
114 #include "termopts.h"
115 #include "commands.h"
116 #include "keyboard.h"
117 #include "blockinput.h"
118 #include "dispextern.h"
119 #include "composite.h"
120 #include "atimer.h"
122 Lisp_Object Qprocessp;
123 Lisp_Object Qrun, Qstop, Qsignal;
124 Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
125 Lisp_Object Qlocal, Qipv4, Qdatagram;
126 Lisp_Object Qreal, Qnetwork, Qserial;
127 #ifdef AF_INET6
128 Lisp_Object Qipv6;
129 #endif
130 Lisp_Object QCport, QCspeed, QCprocess;
131 Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
132 Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
133 Lisp_Object QCname, QCbuffer, QChost, QCservice, QCtype;
134 Lisp_Object QClocal, QCremote, QCcoding;
135 Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
136 Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
137 Lisp_Object Qlast_nonmenu_event;
138 /* QCfamily is declared and initialized in xfaces.c,
139 QCfilter in keyboard.c. */
140 extern Lisp_Object QCfamily, QCfilter;
142 /* Qexit is declared and initialized in eval.c. */
144 /* QCfamily is defined in xfaces.c. */
145 extern Lisp_Object QCfamily;
146 /* QCfilter is defined in keyboard.c. */
147 extern Lisp_Object QCfilter;
149 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
150 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
151 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
152 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
154 #ifdef HAVE_SOCKETS
155 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
156 #define NETCONN1_P(p) (EQ ((p)->type, Qnetwork))
157 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
158 #define SERIALCONN1_P(p) (EQ ((p)->type, Qserial))
159 #else
160 #define NETCONN_P(p) 0
161 #define NETCONN1_P(p) 0
162 #define SERIALCONN_P(p) 0
163 #define SERIALCONN1_P(p) 0
164 #endif /* HAVE_SOCKETS */
166 /* Define first descriptor number available for subprocesses. */
167 #define FIRST_PROC_DESC 3
169 /* Define SIGCHLD as an alias for SIGCLD. There are many conditionals
170 testing SIGCHLD. */
172 #if !defined (SIGCHLD) && defined (SIGCLD)
173 #define SIGCHLD SIGCLD
174 #endif /* SIGCLD */
176 #include "syssignal.h"
178 #include "syswait.h"
180 extern char *get_operating_system_release ();
182 /* Serial processes require termios or Windows. */
183 #if defined (HAVE_TERMIOS) || defined (WINDOWSNT)
184 #define HAVE_SERIAL
185 #endif
187 #ifdef HAVE_SERIAL
188 /* From sysdep.c or w32.c */
189 extern int serial_open (char *port);
190 extern void serial_configure (struct Lisp_Process *p, Lisp_Object contact);
191 #endif
193 #ifndef USE_CRT_DLL
194 extern int errno;
195 #endif
197 #ifndef HAVE_H_ERRNO
198 extern int h_errno;
199 #endif
201 /* t means use pty, nil means use a pipe,
202 maybe other values to come. */
203 static Lisp_Object Vprocess_connection_type;
205 /* These next two vars are non-static since sysdep.c uses them in the
206 emulation of `select'. */
207 /* Number of events of change of status of a process. */
208 int process_tick;
209 /* Number of events for which the user or sentinel has been notified. */
210 int update_tick;
212 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
214 #ifdef BROKEN_NON_BLOCKING_CONNECT
215 #undef NON_BLOCKING_CONNECT
216 #else
217 #ifndef NON_BLOCKING_CONNECT
218 #ifdef HAVE_SOCKETS
219 #ifdef HAVE_SELECT
220 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
221 #if defined (O_NONBLOCK) || defined (O_NDELAY)
222 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
223 #define NON_BLOCKING_CONNECT
224 #endif /* EWOULDBLOCK || EINPROGRESS */
225 #endif /* O_NONBLOCK || O_NDELAY */
226 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
227 #endif /* HAVE_SELECT */
228 #endif /* HAVE_SOCKETS */
229 #endif /* NON_BLOCKING_CONNECT */
230 #endif /* BROKEN_NON_BLOCKING_CONNECT */
232 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
233 this system. We need to read full packets, so we need a
234 "non-destructive" select. So we require either native select,
235 or emulation of select using FIONREAD. */
237 #ifdef BROKEN_DATAGRAM_SOCKETS
238 #undef DATAGRAM_SOCKETS
239 #else
240 #ifndef DATAGRAM_SOCKETS
241 #ifdef HAVE_SOCKETS
242 #if defined (HAVE_SELECT) || defined (FIONREAD)
243 #if defined (HAVE_SENDTO) && defined (HAVE_RECVFROM) && defined (EMSGSIZE)
244 #define DATAGRAM_SOCKETS
245 #endif /* HAVE_SENDTO && HAVE_RECVFROM && EMSGSIZE */
246 #endif /* HAVE_SELECT || FIONREAD */
247 #endif /* HAVE_SOCKETS */
248 #endif /* DATAGRAM_SOCKETS */
249 #endif /* BROKEN_DATAGRAM_SOCKETS */
251 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
252 #ifdef EMACS_HAS_USECS
253 #define ADAPTIVE_READ_BUFFERING
254 #endif
255 #endif
257 #ifdef ADAPTIVE_READ_BUFFERING
258 #define READ_OUTPUT_DELAY_INCREMENT 10000
259 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
260 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
262 /* Number of processes which have a non-zero read_output_delay,
263 and therefore might be delayed for adaptive read buffering. */
265 static int process_output_delay_count;
267 /* Non-zero if any process has non-nil read_output_skip. */
269 static int process_output_skip;
271 /* Non-nil means to delay reading process output to improve buffering.
272 A value of t means that delay is reset after each send, any other
273 non-nil value does not reset the delay. A value of nil disables
274 adaptive read buffering completely. */
275 static Lisp_Object Vprocess_adaptive_read_buffering;
276 #else
277 #define process_output_delay_count 0
278 #endif
281 #include "sysselect.h"
283 static int keyboard_bit_set P_ ((SELECT_TYPE *));
284 static void deactivate_process P_ ((Lisp_Object));
285 static void status_notify P_ ((struct Lisp_Process *));
286 static int read_process_output P_ ((Lisp_Object, int));
288 /* If we support a window system, turn on the code to poll periodically
289 to detect C-g. It isn't actually used when doing interrupt input. */
290 #ifdef HAVE_WINDOW_SYSTEM
291 #define POLL_FOR_INPUT
292 #endif
294 static Lisp_Object get_process ();
295 static void exec_sentinel ();
297 extern EMACS_TIME timer_check ();
298 extern int timers_run;
300 /* Mask of bits indicating the descriptors that we wait for input on. */
302 static SELECT_TYPE input_wait_mask;
304 /* Mask that excludes keyboard input descriptor(s). */
306 static SELECT_TYPE non_keyboard_wait_mask;
308 /* Mask that excludes process input descriptor(s). */
310 static SELECT_TYPE non_process_wait_mask;
312 /* Mask for the gpm mouse input descriptor. */
314 static SELECT_TYPE gpm_wait_mask;
316 #ifdef NON_BLOCKING_CONNECT
317 /* Mask of bits indicating the descriptors that we wait for connect to
318 complete on. Once they complete, they are removed from this mask
319 and added to the input_wait_mask and non_keyboard_wait_mask. */
321 static SELECT_TYPE connect_wait_mask;
323 /* Number of bits set in connect_wait_mask. */
324 static int num_pending_connects;
326 #define IF_NON_BLOCKING_CONNECT(s) s
327 #else
328 #define IF_NON_BLOCKING_CONNECT(s)
329 #endif
331 /* The largest descriptor currently in use for a process object. */
332 static int max_process_desc;
334 /* The largest descriptor currently in use for keyboard input. */
335 static int max_keyboard_desc;
337 /* The largest descriptor currently in use for gpm mouse input. */
338 static int max_gpm_desc;
340 /* Nonzero means delete a process right away if it exits. */
341 static int delete_exited_processes;
343 /* Indexed by descriptor, gives the process (if any) for that descriptor */
344 Lisp_Object chan_process[MAXDESC];
346 /* Alist of elements (NAME . PROCESS) */
347 Lisp_Object Vprocess_alist;
349 /* Buffered-ahead input char from process, indexed by channel.
350 -1 means empty (no char is buffered).
351 Used on sys V where the only way to tell if there is any
352 output from the process is to read at least one char.
353 Always -1 on systems that support FIONREAD. */
355 /* Don't make static; need to access externally. */
356 int proc_buffered_char[MAXDESC];
358 /* Table of `struct coding-system' for each process. */
359 static struct coding_system *proc_decode_coding_system[MAXDESC];
360 static struct coding_system *proc_encode_coding_system[MAXDESC];
362 #ifdef DATAGRAM_SOCKETS
363 /* Table of `partner address' for datagram sockets. */
364 struct sockaddr_and_len {
365 struct sockaddr *sa;
366 int len;
367 } datagram_address[MAXDESC];
368 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
369 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
370 #else
371 #define DATAGRAM_CHAN_P(chan) (0)
372 #define DATAGRAM_CONN_P(proc) (0)
373 #endif
375 /* Maximum number of bytes to send to a pty without an eof. */
376 static int pty_max_bytes;
378 /* Nonzero means don't run process sentinels. This is used
379 when exiting. */
380 int inhibit_sentinels;
382 #ifdef HAVE_PTYS
383 #ifdef HAVE_PTY_H
384 #include <pty.h>
385 #endif
386 /* The file name of the pty opened by allocate_pty. */
388 static char pty_name[24];
389 #endif
391 /* Compute the Lisp form of the process status, p->status, from
392 the numeric status that was returned by `wait'. */
394 static Lisp_Object status_convert (int);
396 static void
397 update_status (p)
398 struct Lisp_Process *p;
400 eassert (p->raw_status_new);
401 p->status = status_convert (p->raw_status);
402 p->raw_status_new = 0;
405 /* Convert a process status word in Unix format to
406 the list that we use internally. */
408 static Lisp_Object
409 status_convert (int w)
411 if (WIFSTOPPED (w))
412 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
413 else if (WIFEXITED (w))
414 return Fcons (Qexit, Fcons (make_number (WRETCODE (w)),
415 WCOREDUMP (w) ? Qt : Qnil));
416 else if (WIFSIGNALED (w))
417 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
418 WCOREDUMP (w) ? Qt : Qnil));
419 else
420 return Qrun;
423 /* Given a status-list, extract the three pieces of information
424 and store them individually through the three pointers. */
426 static void
427 decode_status (l, symbol, code, coredump)
428 Lisp_Object l;
429 Lisp_Object *symbol;
430 int *code;
431 int *coredump;
433 Lisp_Object tem;
435 if (SYMBOLP (l))
437 *symbol = l;
438 *code = 0;
439 *coredump = 0;
441 else
443 *symbol = XCAR (l);
444 tem = XCDR (l);
445 *code = XFASTINT (XCAR (tem));
446 tem = XCDR (tem);
447 *coredump = !NILP (tem);
451 /* Return a string describing a process status list. */
453 static Lisp_Object
454 status_message (p)
455 struct Lisp_Process *p;
457 Lisp_Object status = p->status;
458 Lisp_Object symbol;
459 int code, coredump;
460 Lisp_Object string, string2;
462 decode_status (status, &symbol, &code, &coredump);
464 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
466 char *signame;
467 int c;
468 synchronize_system_messages_locale ();
469 signame = strsignal (code);
470 if (signame == 0)
471 signame = "unknown";
472 string = build_string (signame);
473 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
474 c = STRING_CHAR ((char *) SDATA (string), 0);
475 Faset (string, 0, make_number (DOWNCASE (c)));
476 return concat2 (string, string2);
478 else if (EQ (symbol, Qexit))
480 if (NETCONN1_P (p))
481 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
482 if (code == 0)
483 return build_string ("finished\n");
484 string = Fnumber_to_string (make_number (code));
485 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
486 return concat3 (build_string ("exited abnormally with code "),
487 string, string2);
489 else if (EQ (symbol, Qfailed))
491 string = Fnumber_to_string (make_number (code));
492 string2 = build_string ("\n");
493 return concat3 (build_string ("failed with code "),
494 string, string2);
496 else
497 return Fcopy_sequence (Fsymbol_name (symbol));
500 #ifdef HAVE_PTYS
502 /* Open an available pty, returning a file descriptor.
503 Return -1 on failure.
504 The file name of the terminal corresponding to the pty
505 is left in the variable pty_name. */
507 static int
508 allocate_pty ()
510 register int c, i;
511 int fd;
513 #ifdef PTY_ITERATION
514 PTY_ITERATION
515 #else
516 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
517 for (i = 0; i < 16; i++)
518 #endif
520 struct stat stb; /* Used in some PTY_OPEN. */
521 #ifdef PTY_NAME_SPRINTF
522 PTY_NAME_SPRINTF
523 #else
524 sprintf (pty_name, "/dev/pty%c%x", c, i);
525 #endif /* no PTY_NAME_SPRINTF */
527 #ifdef PTY_OPEN
528 PTY_OPEN;
529 #else /* no PTY_OPEN */
531 { /* Some systems name their pseudoterminals so that there are gaps in
532 the usual sequence - for example, on HP9000/S700 systems, there
533 are no pseudoterminals with names ending in 'f'. So we wait for
534 three failures in a row before deciding that we've reached the
535 end of the ptys. */
536 int failed_count = 0;
538 if (stat (pty_name, &stb) < 0)
540 failed_count++;
541 if (failed_count >= 3)
542 return -1;
544 else
545 failed_count = 0;
547 # ifdef O_NONBLOCK
548 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
549 # else
550 fd = emacs_open (pty_name, O_RDWR | O_NDELAY, 0);
551 # endif
553 #endif /* no PTY_OPEN */
555 if (fd >= 0)
557 /* check to make certain that both sides are available
558 this avoids a nasty yet stupid bug in rlogins */
559 #ifdef PTY_TTY_NAME_SPRINTF
560 PTY_TTY_NAME_SPRINTF
561 #else
562 sprintf (pty_name, "/dev/tty%c%x", c, i);
563 #endif /* no PTY_TTY_NAME_SPRINTF */
564 if (access (pty_name, 6) != 0)
566 emacs_close (fd);
567 # ifndef __sgi
568 continue;
569 # else
570 return -1;
571 # endif /* __sgi */
573 setup_pty (fd);
574 return fd;
577 return -1;
579 #endif /* HAVE_PTYS */
581 static Lisp_Object
582 make_process (name)
583 Lisp_Object name;
585 register Lisp_Object val, tem, name1;
586 register struct Lisp_Process *p;
587 char suffix[10];
588 register int i;
590 p = allocate_process ();
592 p->infd = -1;
593 p->outfd = -1;
594 p->tick = 0;
595 p->update_tick = 0;
596 p->pid = 0;
597 p->pty_flag = 0;
598 p->raw_status_new = 0;
599 p->status = Qrun;
600 p->mark = Fmake_marker ();
601 p->kill_without_query = 0;
603 #ifdef ADAPTIVE_READ_BUFFERING
604 p->adaptive_read_buffering = 0;
605 p->read_output_delay = 0;
606 p->read_output_skip = 0;
607 #endif
609 /* If name is already in use, modify it until it is unused. */
611 name1 = name;
612 for (i = 1; ; i++)
614 tem = Fget_process (name1);
615 if (NILP (tem)) break;
616 sprintf (suffix, "<%d>", i);
617 name1 = concat2 (name, build_string (suffix));
619 name = name1;
620 p->name = name;
621 XSETPROCESS (val, p);
622 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
623 return val;
626 static void
627 remove_process (proc)
628 register Lisp_Object proc;
630 register Lisp_Object pair;
632 pair = Frassq (proc, Vprocess_alist);
633 Vprocess_alist = Fdelq (pair, Vprocess_alist);
635 deactivate_process (proc);
638 /* Setup coding systems of PROCESS. */
640 void
641 setup_process_coding_systems (process)
642 Lisp_Object process;
644 struct Lisp_Process *p = XPROCESS (process);
645 int inch = p->infd;
646 int outch = p->outfd;
647 Lisp_Object coding_system;
649 if (inch < 0 || outch < 0)
650 return;
652 if (!proc_decode_coding_system[inch])
653 proc_decode_coding_system[inch]
654 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
655 coding_system = p->decode_coding_system;
656 if (! NILP (p->filter))
658 else if (BUFFERP (p->buffer))
660 if (NILP (XBUFFER (p->buffer)->enable_multibyte_characters))
661 coding_system = raw_text_coding_system (coding_system);
663 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
665 if (!proc_encode_coding_system[outch])
666 proc_encode_coding_system[outch]
667 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
668 setup_coding_system (p->encode_coding_system,
669 proc_encode_coding_system[outch]);
672 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
673 doc: /* Return t if OBJECT is a process. */)
674 (object)
675 Lisp_Object object;
677 return PROCESSP (object) ? Qt : Qnil;
680 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
681 doc: /* Return the process named NAME, or nil if there is none. */)
682 (name)
683 register Lisp_Object name;
685 if (PROCESSP (name))
686 return name;
687 CHECK_STRING (name);
688 return Fcdr (Fassoc (name, Vprocess_alist));
691 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
692 doc: /* Return the (or a) process associated with BUFFER.
693 BUFFER may be a buffer or the name of one. */)
694 (buffer)
695 register Lisp_Object buffer;
697 register Lisp_Object buf, tail, proc;
699 if (NILP (buffer)) return Qnil;
700 buf = Fget_buffer (buffer);
701 if (NILP (buf)) return Qnil;
703 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
705 proc = Fcdr (XCAR (tail));
706 if (PROCESSP (proc) && EQ (XPROCESS (proc)->buffer, buf))
707 return proc;
709 return Qnil;
712 /* This is how commands for the user decode process arguments. It
713 accepts a process, a process name, a buffer, a buffer name, or nil.
714 Buffers denote the first process in the buffer, and nil denotes the
715 current buffer. */
717 static Lisp_Object
718 get_process (name)
719 register Lisp_Object name;
721 register Lisp_Object proc, obj;
722 if (STRINGP (name))
724 obj = Fget_process (name);
725 if (NILP (obj))
726 obj = Fget_buffer (name);
727 if (NILP (obj))
728 error ("Process %s does not exist", SDATA (name));
730 else if (NILP (name))
731 obj = Fcurrent_buffer ();
732 else
733 obj = name;
735 /* Now obj should be either a buffer object or a process object.
737 if (BUFFERP (obj))
739 proc = Fget_buffer_process (obj);
740 if (NILP (proc))
741 error ("Buffer %s has no process", SDATA (XBUFFER (obj)->name));
743 else
745 CHECK_PROCESS (obj);
746 proc = obj;
748 return proc;
752 #ifdef SIGCHLD
753 /* Fdelete_process promises to immediately forget about the process, but in
754 reality, Emacs needs to remember those processes until they have been
755 treated by sigchld_handler; otherwise this handler would consider the
756 process as being synchronous and say that the synchronous process is
757 dead. */
758 static Lisp_Object deleted_pid_list;
759 #endif
761 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
762 doc: /* Delete PROCESS: kill it and forget about it immediately.
763 PROCESS may be a process, a buffer, the name of a process or buffer, or
764 nil, indicating the current buffer's process. */)
765 (process)
766 register Lisp_Object process;
768 register struct Lisp_Process *p;
770 process = get_process (process);
771 p = XPROCESS (process);
773 p->raw_status_new = 0;
774 if (NETCONN1_P (p) || SERIALCONN1_P (p))
776 p->status = Fcons (Qexit, Fcons (make_number (0), Qnil));
777 p->tick = ++process_tick;
778 status_notify (p);
780 else if (p->infd >= 0)
782 #ifdef SIGCHLD
783 Lisp_Object symbol;
784 /* Assignment to EMACS_INT stops GCC whining about limited range
785 of data type. */
786 EMACS_INT pid = p->pid;
788 /* No problem storing the pid here, as it is still in Vprocess_alist. */
789 deleted_pid_list = Fcons (make_fixnum_or_float (pid),
790 /* GC treated elements set to nil. */
791 Fdelq (Qnil, deleted_pid_list));
792 /* If the process has already signaled, remove it from the list. */
793 if (p->raw_status_new)
794 update_status (p);
795 symbol = p->status;
796 if (CONSP (p->status))
797 symbol = XCAR (p->status);
798 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit))
799 deleted_pid_list
800 = Fdelete (make_fixnum_or_float (pid), deleted_pid_list);
801 else
802 #endif
804 Fkill_process (process, Qnil);
805 /* Do this now, since remove_process will make sigchld_handler do nothing. */
806 p->status
807 = Fcons (Qsignal, Fcons (make_number (SIGKILL), Qnil));
808 p->tick = ++process_tick;
809 status_notify (p);
812 remove_process (process);
813 return Qnil;
816 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
817 doc: /* Return the status of PROCESS.
818 The returned value is one of the following symbols:
819 run -- for a process that is running.
820 stop -- for a process stopped but continuable.
821 exit -- for a process that has exited.
822 signal -- for a process that has got a fatal signal.
823 open -- for a network stream connection that is open.
824 listen -- for a network stream server that is listening.
825 closed -- for a network stream connection that is closed.
826 connect -- when waiting for a non-blocking connection to complete.
827 failed -- when a non-blocking connection has failed.
828 nil -- if arg is a process name and no such process exists.
829 PROCESS may be a process, a buffer, the name of a process, or
830 nil, indicating the current buffer's process. */)
831 (process)
832 register Lisp_Object process;
834 register struct Lisp_Process *p;
835 register Lisp_Object status;
837 if (STRINGP (process))
838 process = Fget_process (process);
839 else
840 process = get_process (process);
842 if (NILP (process))
843 return process;
845 p = XPROCESS (process);
846 if (p->raw_status_new)
847 update_status (p);
848 status = p->status;
849 if (CONSP (status))
850 status = XCAR (status);
851 if (NETCONN1_P (p) || SERIALCONN1_P (p))
853 if (EQ (status, Qexit))
854 status = Qclosed;
855 else if (EQ (p->command, Qt))
856 status = Qstop;
857 else if (EQ (status, Qrun))
858 status = Qopen;
860 return status;
863 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
864 1, 1, 0,
865 doc: /* Return the exit status of PROCESS or the signal number that killed it.
866 If PROCESS has not yet exited or died, return 0. */)
867 (process)
868 register Lisp_Object process;
870 CHECK_PROCESS (process);
871 if (XPROCESS (process)->raw_status_new)
872 update_status (XPROCESS (process));
873 if (CONSP (XPROCESS (process)->status))
874 return XCAR (XCDR (XPROCESS (process)->status));
875 return make_number (0);
878 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
879 doc: /* Return the process id of PROCESS.
880 This is the pid of the external process which PROCESS uses or talks to.
881 For a network connection, this value is nil. */)
882 (process)
883 register Lisp_Object process;
885 /* Assignment to EMACS_INT stops GCC whining about limited range of
886 data type. */
887 EMACS_INT pid;
889 CHECK_PROCESS (process);
890 pid = XPROCESS (process)->pid;
891 return (pid ? make_fixnum_or_float (pid) : Qnil);
894 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
895 doc: /* Return the name of PROCESS, as a string.
896 This is the name of the program invoked in PROCESS,
897 possibly modified to make it unique among process names. */)
898 (process)
899 register Lisp_Object process;
901 CHECK_PROCESS (process);
902 return XPROCESS (process)->name;
905 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
906 doc: /* Return the command that was executed to start PROCESS.
907 This is a list of strings, the first string being the program executed
908 and the rest of the strings being the arguments given to it.
909 For a network or serial process, this is nil (process is running) or t
910 \(process is stopped). */)
911 (process)
912 register Lisp_Object process;
914 CHECK_PROCESS (process);
915 return XPROCESS (process)->command;
918 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
919 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
920 This is the terminal that the process itself reads and writes on,
921 not the name of the pty that Emacs uses to talk with that terminal. */)
922 (process)
923 register Lisp_Object process;
925 CHECK_PROCESS (process);
926 return XPROCESS (process)->tty_name;
929 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
930 2, 2, 0,
931 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil). */)
932 (process, buffer)
933 register Lisp_Object process, buffer;
935 struct Lisp_Process *p;
937 CHECK_PROCESS (process);
938 if (!NILP (buffer))
939 CHECK_BUFFER (buffer);
940 p = XPROCESS (process);
941 p->buffer = buffer;
942 if (NETCONN1_P (p) || SERIALCONN1_P (p))
943 p->childp = Fplist_put (p->childp, QCbuffer, buffer);
944 setup_process_coding_systems (process);
945 return buffer;
948 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
949 1, 1, 0,
950 doc: /* Return the buffer PROCESS is associated with.
951 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
952 (process)
953 register Lisp_Object process;
955 CHECK_PROCESS (process);
956 return XPROCESS (process)->buffer;
959 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
960 1, 1, 0,
961 doc: /* Return the marker for the end of the last output from PROCESS. */)
962 (process)
963 register Lisp_Object process;
965 CHECK_PROCESS (process);
966 return XPROCESS (process)->mark;
969 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
970 2, 2, 0,
971 doc: /* Give PROCESS the filter function FILTER; nil means no filter.
972 A value of t means stop accepting output from the process.
974 When a process has a filter, its buffer is not used for output.
975 Instead, each time it does output, the entire string of output is
976 passed to the filter.
978 The filter gets two arguments: the process and the string of output.
979 The string argument is normally a multibyte string, except:
980 - if the process' input coding system is no-conversion or raw-text,
981 it is a unibyte string (the non-converted input), or else
982 - if `default-enable-multibyte-characters' is nil, it is a unibyte
983 string (the result of converting the decoded input multibyte
984 string to unibyte with `string-make-unibyte'). */)
985 (process, filter)
986 register Lisp_Object process, filter;
988 struct Lisp_Process *p;
990 CHECK_PROCESS (process);
991 p = XPROCESS (process);
993 /* Don't signal an error if the process' input file descriptor
994 is closed. This could make debugging Lisp more difficult,
995 for example when doing something like
997 (setq process (start-process ...))
998 (debug)
999 (set-process-filter process ...) */
1001 if (p->infd >= 0)
1003 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1005 FD_CLR (p->infd, &input_wait_mask);
1006 FD_CLR (p->infd, &non_keyboard_wait_mask);
1008 else if (EQ (p->filter, Qt)
1009 /* Network or serial process not stopped: */
1010 && !EQ (p->command, Qt))
1012 FD_SET (p->infd, &input_wait_mask);
1013 FD_SET (p->infd, &non_keyboard_wait_mask);
1017 p->filter = filter;
1018 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1019 p->childp = Fplist_put (p->childp, QCfilter, filter);
1020 setup_process_coding_systems (process);
1021 return filter;
1024 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1025 1, 1, 0,
1026 doc: /* Returns the filter function of PROCESS; nil if none.
1027 See `set-process-filter' for more info on filter functions. */)
1028 (process)
1029 register Lisp_Object process;
1031 CHECK_PROCESS (process);
1032 return XPROCESS (process)->filter;
1035 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1036 2, 2, 0,
1037 doc: /* Give PROCESS the sentinel SENTINEL; nil for none.
1038 The sentinel is called as a function when the process changes state.
1039 It gets two arguments: the process, and a string describing the change. */)
1040 (process, sentinel)
1041 register Lisp_Object process, sentinel;
1043 struct Lisp_Process *p;
1045 CHECK_PROCESS (process);
1046 p = XPROCESS (process);
1048 p->sentinel = sentinel;
1049 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1050 p->childp = Fplist_put (p->childp, QCsentinel, sentinel);
1051 return sentinel;
1054 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1055 1, 1, 0,
1056 doc: /* Return the sentinel of PROCESS; nil if none.
1057 See `set-process-sentinel' for more info on sentinels. */)
1058 (process)
1059 register Lisp_Object process;
1061 CHECK_PROCESS (process);
1062 return XPROCESS (process)->sentinel;
1065 DEFUN ("set-process-window-size", Fset_process_window_size,
1066 Sset_process_window_size, 3, 3, 0,
1067 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1068 (process, height, width)
1069 register Lisp_Object process, height, width;
1071 CHECK_PROCESS (process);
1072 CHECK_NATNUM (height);
1073 CHECK_NATNUM (width);
1075 if (XPROCESS (process)->infd < 0
1076 || set_window_size (XPROCESS (process)->infd,
1077 XINT (height), XINT (width)) <= 0)
1078 return Qnil;
1079 else
1080 return Qt;
1083 DEFUN ("set-process-inherit-coding-system-flag",
1084 Fset_process_inherit_coding_system_flag,
1085 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1086 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1087 If the second argument FLAG is non-nil, then the variable
1088 `buffer-file-coding-system' of the buffer associated with PROCESS
1089 will be bound to the value of the coding system used to decode
1090 the process output.
1092 This is useful when the coding system specified for the process buffer
1093 leaves either the character code conversion or the end-of-line conversion
1094 unspecified, or if the coding system used to decode the process output
1095 is more appropriate for saving the process buffer.
1097 Binding the variable `inherit-process-coding-system' to non-nil before
1098 starting the process is an alternative way of setting the inherit flag
1099 for the process which will run. */)
1100 (process, flag)
1101 register Lisp_Object process, flag;
1103 CHECK_PROCESS (process);
1104 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1105 return flag;
1108 DEFUN ("process-inherit-coding-system-flag",
1109 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
1110 1, 1, 0,
1111 doc: /* Return the value of inherit-coding-system flag for PROCESS.
1112 If this flag is t, `buffer-file-coding-system' of the buffer
1113 associated with PROCESS will inherit the coding system used to decode
1114 the process output. */)
1115 (process)
1116 register Lisp_Object process;
1118 CHECK_PROCESS (process);
1119 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
1122 DEFUN ("set-process-query-on-exit-flag",
1123 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1124 2, 2, 0,
1125 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1126 If the second argument FLAG is non-nil, Emacs will query the user before
1127 exiting if PROCESS is running. */)
1128 (process, flag)
1129 register Lisp_Object process, flag;
1131 CHECK_PROCESS (process);
1132 XPROCESS (process)->kill_without_query = NILP (flag);
1133 return flag;
1136 DEFUN ("process-query-on-exit-flag",
1137 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1138 1, 1, 0,
1139 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1140 (process)
1141 register Lisp_Object process;
1143 CHECK_PROCESS (process);
1144 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1147 #ifdef DATAGRAM_SOCKETS
1148 Lisp_Object Fprocess_datagram_address ();
1149 #endif
1151 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1152 1, 2, 0,
1153 doc: /* Return the contact info of PROCESS; t for a real child.
1154 For a network or serial connection, the value depends on the optional
1155 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1156 SERVICE) for a network connection or (PORT SPEED) for a serial
1157 connection. If KEY is t, the complete contact information for the
1158 connection is returned, else the specific value for the keyword KEY is
1159 returned. See `make-network-process' or `make-serial-process' for a
1160 list of keywords. */)
1161 (process, key)
1162 register Lisp_Object process, key;
1164 Lisp_Object contact;
1166 CHECK_PROCESS (process);
1167 contact = XPROCESS (process)->childp;
1169 #ifdef DATAGRAM_SOCKETS
1170 if (DATAGRAM_CONN_P (process)
1171 && (EQ (key, Qt) || EQ (key, QCremote)))
1172 contact = Fplist_put (contact, QCremote,
1173 Fprocess_datagram_address (process));
1174 #endif
1176 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1177 return contact;
1178 if (NILP (key) && NETCONN_P (process))
1179 return Fcons (Fplist_get (contact, QChost),
1180 Fcons (Fplist_get (contact, QCservice), Qnil));
1181 if (NILP (key) && SERIALCONN_P (process))
1182 return Fcons (Fplist_get (contact, QCport),
1183 Fcons (Fplist_get (contact, QCspeed), Qnil));
1184 return Fplist_get (contact, key);
1187 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1188 1, 1, 0,
1189 doc: /* Return the plist of PROCESS. */)
1190 (process)
1191 register Lisp_Object process;
1193 CHECK_PROCESS (process);
1194 return XPROCESS (process)->plist;
1197 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1198 2, 2, 0,
1199 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1200 (process, plist)
1201 register Lisp_Object process, plist;
1203 CHECK_PROCESS (process);
1204 CHECK_LIST (plist);
1206 XPROCESS (process)->plist = plist;
1207 return plist;
1210 #if 0 /* Turned off because we don't currently record this info
1211 in the process. Perhaps add it. */
1212 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1213 doc: /* Return the connection type of PROCESS.
1214 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1215 a socket connection. */)
1216 (process)
1217 Lisp_Object process;
1219 return XPROCESS (process)->type;
1221 #endif
1223 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1224 doc: /* Return the connection type of PROCESS.
1225 The value is either the symbol `real', `network', or `serial'.
1226 PROCESS may be a process, a buffer, the name of a process or buffer, or
1227 nil, indicating the current buffer's process. */)
1228 (process)
1229 Lisp_Object process;
1231 Lisp_Object proc;
1232 proc = get_process (process);
1233 return XPROCESS (proc)->type;
1236 #ifdef HAVE_SOCKETS
1237 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1238 1, 2, 0,
1239 doc: /* Convert network ADDRESS from internal format to a string.
1240 A 4 or 5 element vector represents an IPv4 address (with port number).
1241 An 8 or 9 element vector represents an IPv6 address (with port number).
1242 If optional second argument OMIT-PORT is non-nil, don't include a port
1243 number in the string, even when present in ADDRESS.
1244 Returns nil if format of ADDRESS is invalid. */)
1245 (address, omit_port)
1246 Lisp_Object address, omit_port;
1248 if (NILP (address))
1249 return Qnil;
1251 if (STRINGP (address)) /* AF_LOCAL */
1252 return address;
1254 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1256 register struct Lisp_Vector *p = XVECTOR (address);
1257 Lisp_Object args[10];
1258 int nargs, i;
1260 if (p->size == 4 || (p->size == 5 && !NILP (omit_port)))
1262 args[0] = build_string ("%d.%d.%d.%d");
1263 nargs = 4;
1265 else if (p->size == 5)
1267 args[0] = build_string ("%d.%d.%d.%d:%d");
1268 nargs = 5;
1270 else if (p->size == 8 || (p->size == 9 && !NILP (omit_port)))
1272 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1273 nargs = 8;
1275 else if (p->size == 9)
1277 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1278 nargs = 9;
1280 else
1281 return Qnil;
1283 for (i = 0; i < nargs; i++)
1285 EMACS_INT element = XINT (p->contents[i]);
1287 if (element < 0 || element > 65535)
1288 return Qnil;
1290 if (nargs <= 5 /* IPv4 */
1291 && i < 4 /* host, not port */
1292 && element > 255)
1293 return Qnil;
1295 args[i+1] = p->contents[i];
1298 return Fformat (nargs+1, args);
1301 if (CONSP (address))
1303 Lisp_Object args[2];
1304 args[0] = build_string ("<Family %d>");
1305 args[1] = Fcar (address);
1306 return Fformat (2, args);
1309 return Qnil;
1311 #endif
1313 static Lisp_Object
1314 list_processes_1 (query_only)
1315 Lisp_Object query_only;
1317 register Lisp_Object tail, tem;
1318 Lisp_Object proc, minspace, tem1;
1319 register struct Lisp_Process *p;
1320 char tembuf[300];
1321 int w_proc, w_buffer, w_tty;
1322 int exited = 0;
1323 Lisp_Object i_status, i_buffer, i_tty, i_command;
1325 w_proc = 4; /* Proc */
1326 w_buffer = 6; /* Buffer */
1327 w_tty = 0; /* Omit if no ttys */
1329 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1331 int i;
1333 proc = Fcdr (XCAR (tail));
1334 p = XPROCESS (proc);
1335 if (NILP (p->type))
1336 continue;
1337 if (!NILP (query_only) && p->kill_without_query)
1338 continue;
1339 if (STRINGP (p->name)
1340 && ( i = SCHARS (p->name), (i > w_proc)))
1341 w_proc = i;
1342 if (!NILP (p->buffer))
1344 if (NILP (XBUFFER (p->buffer)->name))
1346 if (w_buffer < 8)
1347 w_buffer = 8; /* (Killed) */
1349 else if ((i = SCHARS (XBUFFER (p->buffer)->name), (i > w_buffer)))
1350 w_buffer = i;
1352 if (STRINGP (p->tty_name)
1353 && (i = SCHARS (p->tty_name), (i > w_tty)))
1354 w_tty = i;
1357 XSETFASTINT (i_status, w_proc + 1);
1358 XSETFASTINT (i_buffer, XFASTINT (i_status) + 9);
1359 if (w_tty)
1361 XSETFASTINT (i_tty, XFASTINT (i_buffer) + w_buffer + 1);
1362 XSETFASTINT (i_command, XFASTINT (i_tty) + w_tty + 1);
1364 else
1366 i_tty = Qnil;
1367 XSETFASTINT (i_command, XFASTINT (i_buffer) + w_buffer + 1);
1370 XSETFASTINT (minspace, 1);
1372 set_buffer_internal (XBUFFER (Vstandard_output));
1373 current_buffer->undo_list = Qt;
1375 current_buffer->truncate_lines = Qt;
1377 write_string ("Proc", -1);
1378 Findent_to (i_status, minspace); write_string ("Status", -1);
1379 Findent_to (i_buffer, minspace); write_string ("Buffer", -1);
1380 if (!NILP (i_tty))
1382 Findent_to (i_tty, minspace); write_string ("Tty", -1);
1384 Findent_to (i_command, minspace); write_string ("Command", -1);
1385 write_string ("\n", -1);
1387 write_string ("----", -1);
1388 Findent_to (i_status, minspace); write_string ("------", -1);
1389 Findent_to (i_buffer, minspace); write_string ("------", -1);
1390 if (!NILP (i_tty))
1392 Findent_to (i_tty, minspace); write_string ("---", -1);
1394 Findent_to (i_command, minspace); write_string ("-------", -1);
1395 write_string ("\n", -1);
1397 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1399 Lisp_Object symbol;
1401 proc = Fcdr (XCAR (tail));
1402 p = XPROCESS (proc);
1403 if (NILP (p->type))
1404 continue;
1405 if (!NILP (query_only) && p->kill_without_query)
1406 continue;
1408 Finsert (1, &p->name);
1409 Findent_to (i_status, minspace);
1411 if (p->raw_status_new)
1412 update_status (p);
1413 symbol = p->status;
1414 if (CONSP (p->status))
1415 symbol = XCAR (p->status);
1417 if (EQ (symbol, Qsignal))
1419 Lisp_Object tem;
1420 tem = Fcar (Fcdr (p->status));
1421 Fprinc (symbol, Qnil);
1423 else if (NETCONN1_P (p) || SERIALCONN1_P (p))
1425 if (EQ (symbol, Qexit))
1426 write_string ("closed", -1);
1427 else if (EQ (p->command, Qt))
1428 write_string ("stopped", -1);
1429 else if (EQ (symbol, Qrun))
1430 write_string ("open", -1);
1431 else
1432 Fprinc (symbol, Qnil);
1434 else if (SERIALCONN1_P (p))
1436 write_string ("running", -1);
1438 else
1439 Fprinc (symbol, Qnil);
1441 if (EQ (symbol, Qexit))
1443 Lisp_Object tem;
1444 tem = Fcar (Fcdr (p->status));
1445 if (XFASTINT (tem))
1447 sprintf (tembuf, " %d", (int) XFASTINT (tem));
1448 write_string (tembuf, -1);
1452 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit) || EQ (symbol, Qclosed))
1453 exited++;
1455 Findent_to (i_buffer, minspace);
1456 if (NILP (p->buffer))
1457 insert_string ("(none)");
1458 else if (NILP (XBUFFER (p->buffer)->name))
1459 insert_string ("(Killed)");
1460 else
1461 Finsert (1, &XBUFFER (p->buffer)->name);
1463 if (!NILP (i_tty))
1465 Findent_to (i_tty, minspace);
1466 if (STRINGP (p->tty_name))
1467 Finsert (1, &p->tty_name);
1470 Findent_to (i_command, minspace);
1472 if (EQ (p->status, Qlisten))
1474 Lisp_Object port = Fplist_get (p->childp, QCservice);
1475 if (INTEGERP (port))
1476 port = Fnumber_to_string (port);
1477 if (NILP (port))
1478 port = Fformat_network_address (Fplist_get (p->childp, QClocal), Qnil);
1479 sprintf (tembuf, "(network %s server on %s)\n",
1480 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1481 (STRINGP (port) ? (char *)SDATA (port) : "?"));
1482 insert_string (tembuf);
1484 else if (NETCONN1_P (p))
1486 /* For a local socket, there is no host name,
1487 so display service instead. */
1488 Lisp_Object host = Fplist_get (p->childp, QChost);
1489 if (!STRINGP (host))
1491 host = Fplist_get (p->childp, QCservice);
1492 if (INTEGERP (host))
1493 host = Fnumber_to_string (host);
1495 if (NILP (host))
1496 host = Fformat_network_address (Fplist_get (p->childp, QCremote), Qnil);
1497 sprintf (tembuf, "(network %s connection to %s)\n",
1498 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1499 (STRINGP (host) ? (char *)SDATA (host) : "?"));
1500 insert_string (tembuf);
1502 else if (SERIALCONN1_P (p))
1504 Lisp_Object port = Fplist_get (p->childp, QCport);
1505 Lisp_Object speed = Fplist_get (p->childp, QCspeed);
1506 insert_string ("(serial port ");
1507 if (STRINGP (port))
1508 insert_string (SDATA (port));
1509 else
1510 insert_string ("?");
1511 if (INTEGERP (speed))
1513 sprintf (tembuf, " at %d b/s", XINT (speed));
1514 insert_string (tembuf);
1516 insert_string (")\n");
1518 else
1520 tem = p->command;
1521 while (1)
1523 tem1 = Fcar (tem);
1524 Finsert (1, &tem1);
1525 tem = Fcdr (tem);
1526 if (NILP (tem))
1527 break;
1528 insert_string (" ");
1530 insert_string ("\n");
1533 if (exited)
1534 status_notify (NULL);
1535 return Qnil;
1538 DEFUN ("list-processes", Flist_processes, Slist_processes, 0, 1, "P",
1539 doc: /* Display a list of all processes.
1540 If optional argument QUERY-ONLY is non-nil, only processes with
1541 the query-on-exit flag set will be listed.
1542 Any process listed as exited or signaled is actually eliminated
1543 after the listing is made. */)
1544 (query_only)
1545 Lisp_Object query_only;
1547 internal_with_output_to_temp_buffer ("*Process List*",
1548 list_processes_1, query_only);
1549 return Qnil;
1552 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1553 doc: /* Return a list of all processes. */)
1556 return Fmapcar (Qcdr, Vprocess_alist);
1559 /* Starting asynchronous inferior processes. */
1561 static Lisp_Object start_process_unwind ();
1563 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1564 doc: /* Start a program in a subprocess. Return the process object for it.
1565 NAME is name for process. It is modified if necessary to make it unique.
1566 BUFFER is the buffer (or buffer name) to associate with the process.
1568 Process output (both standard output and standard error streams) goes
1569 at end of BUFFER, unless you specify an output stream or filter
1570 function to handle the output. BUFFER may also be nil, meaning that
1571 this process is not associated with any buffer.
1573 PROGRAM is the program file name. It is searched for in PATH.
1574 Remaining arguments are strings to give program as arguments.
1576 If you want to separate standard output from standard error, invoke
1577 the command through a shell and redirect one of them using the shell
1578 syntax.
1580 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1581 (nargs, args)
1582 int nargs;
1583 register Lisp_Object *args;
1585 Lisp_Object buffer, name, program, proc, current_dir, tem;
1586 register unsigned char **new_argv;
1587 register int i;
1588 int count = SPECPDL_INDEX ();
1590 buffer = args[1];
1591 if (!NILP (buffer))
1592 buffer = Fget_buffer_create (buffer);
1594 /* Make sure that the child will be able to chdir to the current
1595 buffer's current directory, or its unhandled equivalent. We
1596 can't just have the child check for an error when it does the
1597 chdir, since it's in a vfork.
1599 We have to GCPRO around this because Fexpand_file_name and
1600 Funhandled_file_name_directory might call a file name handling
1601 function. The argument list is protected by the caller, so all
1602 we really have to worry about is buffer. */
1604 struct gcpro gcpro1, gcpro2;
1606 current_dir = current_buffer->directory;
1608 GCPRO2 (buffer, current_dir);
1610 current_dir = Funhandled_file_name_directory (current_dir);
1611 if (NILP (current_dir))
1612 /* If the file name handler says that current_dir is unreachable, use
1613 a sensible default. */
1614 current_dir = build_string ("~/");
1615 current_dir = expand_and_dir_to_file (current_dir, Qnil);
1616 if (NILP (Ffile_accessible_directory_p (current_dir)))
1617 report_file_error ("Setting current directory",
1618 Fcons (current_buffer->directory, Qnil));
1620 UNGCPRO;
1623 name = args[0];
1624 CHECK_STRING (name);
1626 program = args[2];
1628 CHECK_STRING (program);
1630 proc = make_process (name);
1631 /* If an error occurs and we can't start the process, we want to
1632 remove it from the process list. This means that each error
1633 check in create_process doesn't need to call remove_process
1634 itself; it's all taken care of here. */
1635 record_unwind_protect (start_process_unwind, proc);
1637 XPROCESS (proc)->childp = Qt;
1638 XPROCESS (proc)->plist = Qnil;
1639 XPROCESS (proc)->type = Qreal;
1640 XPROCESS (proc)->buffer = buffer;
1641 XPROCESS (proc)->sentinel = Qnil;
1642 XPROCESS (proc)->filter = Qnil;
1643 XPROCESS (proc)->command = Flist (nargs - 2, args + 2);
1645 #ifdef ADAPTIVE_READ_BUFFERING
1646 XPROCESS (proc)->adaptive_read_buffering
1647 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1648 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1649 #endif
1651 /* Make the process marker point into the process buffer (if any). */
1652 if (BUFFERP (buffer))
1653 set_marker_both (XPROCESS (proc)->mark, buffer,
1654 BUF_ZV (XBUFFER (buffer)),
1655 BUF_ZV_BYTE (XBUFFER (buffer)));
1658 /* Decide coding systems for communicating with the process. Here
1659 we don't setup the structure coding_system nor pay attention to
1660 unibyte mode. They are done in create_process. */
1662 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1663 Lisp_Object coding_systems = Qt;
1664 Lisp_Object val, *args2;
1665 struct gcpro gcpro1, gcpro2;
1667 val = Vcoding_system_for_read;
1668 if (NILP (val))
1670 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
1671 args2[0] = Qstart_process;
1672 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1673 GCPRO2 (proc, current_dir);
1674 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1675 UNGCPRO;
1676 if (CONSP (coding_systems))
1677 val = XCAR (coding_systems);
1678 else if (CONSP (Vdefault_process_coding_system))
1679 val = XCAR (Vdefault_process_coding_system);
1681 XPROCESS (proc)->decode_coding_system = val;
1683 val = Vcoding_system_for_write;
1684 if (NILP (val))
1686 if (EQ (coding_systems, Qt))
1688 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof args2);
1689 args2[0] = Qstart_process;
1690 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1691 GCPRO2 (proc, current_dir);
1692 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1693 UNGCPRO;
1695 if (CONSP (coding_systems))
1696 val = XCDR (coding_systems);
1697 else if (CONSP (Vdefault_process_coding_system))
1698 val = XCDR (Vdefault_process_coding_system);
1700 XPROCESS (proc)->encode_coding_system = val;
1703 /* If program file name is not absolute, search our path for it.
1704 Put the name we will really use in TEM. */
1705 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1706 && !(SCHARS (program) > 1
1707 && IS_DEVICE_SEP (SREF (program, 1))))
1709 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1711 tem = Qnil;
1712 GCPRO4 (name, program, buffer, current_dir);
1713 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1714 UNGCPRO;
1715 if (NILP (tem))
1716 report_file_error ("Searching for program", Fcons (program, Qnil));
1717 tem = Fexpand_file_name (tem, Qnil);
1719 else
1721 if (!NILP (Ffile_directory_p (program)))
1722 error ("Specified program for new process is a directory");
1723 tem = program;
1726 /* If program file name starts with /: for quoting a magic name,
1727 discard that. */
1728 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1729 && SREF (tem, 1) == ':')
1730 tem = Fsubstring (tem, make_number (2), Qnil);
1733 struct gcpro gcpro1;
1734 GCPRO1 (tem);
1736 /* Encode the file name and put it in NEW_ARGV.
1737 That's where the child will use it to execute the program. */
1738 tem = Fcons (ENCODE_FILE (tem), Qnil);
1740 /* Here we encode arguments by the coding system used for sending
1741 data to the process. We don't support using different coding
1742 systems for encoding arguments and for encoding data sent to the
1743 process. */
1745 for (i = 3; i < nargs; i++)
1747 tem = Fcons (args[i], tem);
1748 CHECK_STRING (XCAR (tem));
1749 if (STRING_MULTIBYTE (XCAR (tem)))
1750 XSETCAR (tem,
1751 code_convert_string_norecord
1752 (XCAR (tem), XPROCESS (proc)->encode_coding_system, 1));
1755 UNGCPRO;
1758 /* Now that everything is encoded we can collect the strings into
1759 NEW_ARGV. */
1760 new_argv = (unsigned char **) alloca ((nargs - 1) * sizeof (char *));
1761 new_argv[nargs - 2] = 0;
1763 for (i = nargs - 3; i >= 0; i--)
1765 new_argv[i] = SDATA (XCAR (tem));
1766 tem = XCDR (tem);
1769 XPROCESS (proc)->decoding_buf = make_uninit_string (0);
1770 XPROCESS (proc)->decoding_carryover = 0;
1771 XPROCESS (proc)->encoding_buf = make_uninit_string (0);
1773 XPROCESS (proc)->inherit_coding_system_flag
1774 = !(NILP (buffer) || !inherit_process_coding_system);
1776 create_process (proc, (char **) new_argv, current_dir);
1778 return unbind_to (count, proc);
1781 /* This function is the unwind_protect form for Fstart_process. If
1782 PROC doesn't have its pid set, then we know someone has signaled
1783 an error and the process wasn't started successfully, so we should
1784 remove it from the process list. */
1785 static Lisp_Object
1786 start_process_unwind (proc)
1787 Lisp_Object proc;
1789 if (!PROCESSP (proc))
1790 abort ();
1792 /* Was PROC started successfully? */
1793 if (XPROCESS (proc)->pid <= 0)
1794 remove_process (proc);
1796 return Qnil;
1799 static void
1800 create_process_1 (timer)
1801 struct atimer *timer;
1803 /* Nothing to do. */
1807 #if 0 /* This doesn't work; see the note before sigchld_handler. */
1808 #ifdef USG
1809 #ifdef SIGCHLD
1810 /* Mimic blocking of signals on system V, which doesn't really have it. */
1812 /* Nonzero means we got a SIGCHLD when it was supposed to be blocked. */
1813 int sigchld_deferred;
1815 SIGTYPE
1816 create_process_sigchld ()
1818 signal (SIGCHLD, create_process_sigchld);
1820 sigchld_deferred = 1;
1822 #endif
1823 #endif
1824 #endif
1826 void
1827 create_process (process, new_argv, current_dir)
1828 Lisp_Object process;
1829 char **new_argv;
1830 Lisp_Object current_dir;
1832 int inchannel, outchannel;
1833 pid_t pid;
1834 int sv[2];
1835 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1836 int wait_child_setup[2];
1837 #endif
1838 #ifdef POSIX_SIGNALS
1839 sigset_t procmask;
1840 sigset_t blocked;
1841 struct sigaction sigint_action;
1842 struct sigaction sigquit_action;
1843 #ifdef AIX
1844 struct sigaction sighup_action;
1845 #endif
1846 #else /* !POSIX_SIGNALS */
1847 #if 0
1848 #ifdef SIGCHLD
1849 SIGTYPE (*sigchld)();
1850 #endif
1851 #endif /* 0 */
1852 #endif /* !POSIX_SIGNALS */
1853 /* Use volatile to protect variables from being clobbered by longjmp. */
1854 volatile int forkin, forkout;
1855 volatile int pty_flag = 0;
1856 #ifndef USE_CRT_DLL
1857 extern char **environ;
1858 #endif
1860 inchannel = outchannel = -1;
1862 #ifdef HAVE_PTYS
1863 if (!NILP (Vprocess_connection_type))
1864 outchannel = inchannel = allocate_pty ();
1866 if (inchannel >= 0)
1868 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1869 /* On most USG systems it does not work to open the pty's tty here,
1870 then close it and reopen it in the child. */
1871 #ifdef O_NOCTTY
1872 /* Don't let this terminal become our controlling terminal
1873 (in case we don't have one). */
1874 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1875 #else
1876 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
1877 #endif
1878 if (forkin < 0)
1879 report_file_error ("Opening pty", Qnil);
1880 #else
1881 forkin = forkout = -1;
1882 #endif /* not USG, or USG_SUBTTY_WORKS */
1883 pty_flag = 1;
1885 else
1886 #endif /* HAVE_PTYS */
1888 int tem;
1889 tem = pipe (sv);
1890 if (tem < 0)
1891 report_file_error ("Creating pipe", Qnil);
1892 inchannel = sv[0];
1893 forkout = sv[1];
1894 tem = pipe (sv);
1895 if (tem < 0)
1897 emacs_close (inchannel);
1898 emacs_close (forkout);
1899 report_file_error ("Creating pipe", Qnil);
1901 outchannel = sv[1];
1902 forkin = sv[0];
1905 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1907 int tem;
1909 tem = pipe (wait_child_setup);
1910 if (tem < 0)
1911 report_file_error ("Creating pipe", Qnil);
1912 tem = fcntl (wait_child_setup[1], F_GETFD, 0);
1913 if (tem >= 0)
1914 tem = fcntl (wait_child_setup[1], F_SETFD, tem | FD_CLOEXEC);
1915 if (tem < 0)
1917 emacs_close (wait_child_setup[0]);
1918 emacs_close (wait_child_setup[1]);
1919 report_file_error ("Setting file descriptor flags", Qnil);
1922 #endif
1924 #if 0
1925 /* Replaced by close_process_descs */
1926 set_exclusive_use (inchannel);
1927 set_exclusive_use (outchannel);
1928 #endif
1930 #ifdef O_NONBLOCK
1931 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1932 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1933 #else
1934 #ifdef O_NDELAY
1935 fcntl (inchannel, F_SETFL, O_NDELAY);
1936 fcntl (outchannel, F_SETFL, O_NDELAY);
1937 #endif
1938 #endif
1940 /* Record this as an active process, with its channels.
1941 As a result, child_setup will close Emacs's side of the pipes. */
1942 chan_process[inchannel] = process;
1943 XPROCESS (process)->infd = inchannel;
1944 XPROCESS (process)->outfd = outchannel;
1946 /* Previously we recorded the tty descriptor used in the subprocess.
1947 It was only used for getting the foreground tty process, so now
1948 we just reopen the device (see emacs_get_tty_pgrp) as this is
1949 more portable (see USG_SUBTTY_WORKS above). */
1951 XPROCESS (process)->pty_flag = pty_flag;
1952 XPROCESS (process)->status = Qrun;
1953 setup_process_coding_systems (process);
1955 /* Delay interrupts until we have a chance to store
1956 the new fork's pid in its process structure */
1957 #ifdef POSIX_SIGNALS
1958 sigemptyset (&blocked);
1959 #ifdef SIGCHLD
1960 sigaddset (&blocked, SIGCHLD);
1961 #endif
1962 #ifdef HAVE_WORKING_VFORK
1963 /* On many hosts (e.g. Solaris 2.4), if a vforked child calls `signal',
1964 this sets the parent's signal handlers as well as the child's.
1965 So delay all interrupts whose handlers the child might munge,
1966 and record the current handlers so they can be restored later. */
1967 sigaddset (&blocked, SIGINT ); sigaction (SIGINT , 0, &sigint_action );
1968 sigaddset (&blocked, SIGQUIT); sigaction (SIGQUIT, 0, &sigquit_action);
1969 #ifdef AIX
1970 sigaddset (&blocked, SIGHUP ); sigaction (SIGHUP , 0, &sighup_action );
1971 #endif
1972 #endif /* HAVE_WORKING_VFORK */
1973 sigprocmask (SIG_BLOCK, &blocked, &procmask);
1974 #else /* !POSIX_SIGNALS */
1975 #ifdef SIGCHLD
1976 #if defined (BSD_SYSTEM) || defined (HPUX)
1977 sigsetmask (sigmask (SIGCHLD));
1978 #else /* ordinary USG */
1979 #if 0
1980 sigchld_deferred = 0;
1981 sigchld = signal (SIGCHLD, create_process_sigchld);
1982 #endif
1983 #endif /* ordinary USG */
1984 #endif /* SIGCHLD */
1985 #endif /* !POSIX_SIGNALS */
1987 FD_SET (inchannel, &input_wait_mask);
1988 FD_SET (inchannel, &non_keyboard_wait_mask);
1989 if (inchannel > max_process_desc)
1990 max_process_desc = inchannel;
1992 /* Until we store the proper pid, enable sigchld_handler
1993 to recognize an unknown pid as standing for this process.
1994 It is very important not to let this `marker' value stay
1995 in the table after this function has returned; if it does
1996 it might cause call-process to hang and subsequent asynchronous
1997 processes to get their return values scrambled. */
1998 XPROCESS (process)->pid = -1;
2000 BLOCK_INPUT;
2003 /* child_setup must clobber environ on systems with true vfork.
2004 Protect it from permanent change. */
2005 char **save_environ = environ;
2007 current_dir = ENCODE_FILE (current_dir);
2009 #ifndef WINDOWSNT
2010 pid = vfork ();
2011 if (pid == 0)
2012 #endif /* not WINDOWSNT */
2014 int xforkin = forkin;
2015 int xforkout = forkout;
2017 #if 0 /* This was probably a mistake--it duplicates code later on,
2018 but fails to handle all the cases. */
2019 /* Make sure SIGCHLD is not blocked in the child. */
2020 sigsetmask (SIGEMPTYMASK);
2021 #endif
2023 /* Make the pty be the controlling terminal of the process. */
2024 #ifdef HAVE_PTYS
2025 /* First, disconnect its current controlling terminal. */
2026 #ifdef HAVE_SETSID
2027 /* We tried doing setsid only if pty_flag, but it caused
2028 process_set_signal to fail on SGI when using a pipe. */
2029 setsid ();
2030 /* Make the pty's terminal the controlling terminal. */
2031 if (pty_flag)
2033 #ifdef TIOCSCTTY
2034 /* We ignore the return value
2035 because faith@cs.unc.edu says that is necessary on Linux. */
2036 ioctl (xforkin, TIOCSCTTY, 0);
2037 #endif
2039 #else /* not HAVE_SETSID */
2040 #ifdef USG
2041 /* It's very important to call setpgrp here and no time
2042 afterwards. Otherwise, we lose our controlling tty which
2043 is set when we open the pty. */
2044 setpgrp ();
2045 #endif /* USG */
2046 #endif /* not HAVE_SETSID */
2047 #if defined (HAVE_TERMIOS) && defined (LDISC1)
2048 if (pty_flag && xforkin >= 0)
2050 struct termios t;
2051 tcgetattr (xforkin, &t);
2052 t.c_lflag = LDISC1;
2053 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
2054 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
2056 #else
2057 #if defined (NTTYDISC) && defined (TIOCSETD)
2058 if (pty_flag && xforkin >= 0)
2060 /* Use new line discipline. */
2061 int ldisc = NTTYDISC;
2062 ioctl (xforkin, TIOCSETD, &ldisc);
2064 #endif
2065 #endif
2066 #ifdef TIOCNOTTY
2067 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
2068 can do TIOCSPGRP only to the process's controlling tty. */
2069 if (pty_flag)
2071 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
2072 I can't test it since I don't have 4.3. */
2073 int j = emacs_open ("/dev/tty", O_RDWR, 0);
2074 ioctl (j, TIOCNOTTY, 0);
2075 emacs_close (j);
2076 #ifndef USG
2077 /* In order to get a controlling terminal on some versions
2078 of BSD, it is necessary to put the process in pgrp 0
2079 before it opens the terminal. */
2080 #ifdef HAVE_SETPGID
2081 setpgid (0, 0);
2082 #else
2083 setpgrp (0, 0);
2084 #endif
2085 #endif
2087 #endif /* TIOCNOTTY */
2089 #if !defined (DONT_REOPEN_PTY)
2090 /*** There is a suggestion that this ought to be a
2091 conditional on TIOCSPGRP,
2092 or !(defined (HAVE_SETSID) && defined (TIOCSCTTY)).
2093 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
2094 that system does seem to need this code, even though
2095 both HAVE_SETSID and TIOCSCTTY are defined. */
2096 /* Now close the pty (if we had it open) and reopen it.
2097 This makes the pty the controlling terminal of the subprocess. */
2098 if (pty_flag)
2101 /* I wonder if emacs_close (emacs_open (pty_name, ...))
2102 would work? */
2103 if (xforkin >= 0)
2104 emacs_close (xforkin);
2105 xforkout = xforkin = emacs_open (pty_name, O_RDWR, 0);
2107 if (xforkin < 0)
2109 emacs_write (1, "Couldn't open the pty terminal ", 31);
2110 emacs_write (1, pty_name, strlen (pty_name));
2111 emacs_write (1, "\n", 1);
2112 _exit (1);
2116 #endif /* not DONT_REOPEN_PTY */
2118 #ifdef SETUP_SLAVE_PTY
2119 if (pty_flag)
2121 SETUP_SLAVE_PTY;
2123 #endif /* SETUP_SLAVE_PTY */
2124 #ifdef AIX
2125 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
2126 Now reenable it in the child, so it will die when we want it to. */
2127 if (pty_flag)
2128 signal (SIGHUP, SIG_DFL);
2129 #endif
2130 #endif /* HAVE_PTYS */
2132 signal (SIGINT, SIG_DFL);
2133 signal (SIGQUIT, SIG_DFL);
2135 /* Stop blocking signals in the child. */
2136 #ifdef POSIX_SIGNALS
2137 sigprocmask (SIG_SETMASK, &procmask, 0);
2138 #else /* !POSIX_SIGNALS */
2139 #ifdef SIGCHLD
2140 #if defined (BSD_SYSTEM) || defined (HPUX)
2141 sigsetmask (SIGEMPTYMASK);
2142 #else /* ordinary USG */
2143 #if 0
2144 signal (SIGCHLD, sigchld);
2145 #endif
2146 #endif /* ordinary USG */
2147 #endif /* SIGCHLD */
2148 #endif /* !POSIX_SIGNALS */
2150 if (pty_flag)
2151 child_setup_tty (xforkout);
2152 #ifdef WINDOWSNT
2153 pid = child_setup (xforkin, xforkout, xforkout,
2154 new_argv, 1, current_dir);
2155 #else /* not WINDOWSNT */
2156 #ifdef FD_CLOEXEC
2157 emacs_close (wait_child_setup[0]);
2158 #endif
2159 child_setup (xforkin, xforkout, xforkout,
2160 new_argv, 1, current_dir);
2161 #endif /* not WINDOWSNT */
2163 environ = save_environ;
2166 UNBLOCK_INPUT;
2168 /* This runs in the Emacs process. */
2169 if (pid < 0)
2171 if (forkin >= 0)
2172 emacs_close (forkin);
2173 if (forkin != forkout && forkout >= 0)
2174 emacs_close (forkout);
2176 else
2178 /* vfork succeeded. */
2179 XPROCESS (process)->pid = pid;
2181 #ifdef WINDOWSNT
2182 register_child (pid, inchannel);
2183 #endif /* WINDOWSNT */
2185 /* If the subfork execv fails, and it exits,
2186 this close hangs. I don't know why.
2187 So have an interrupt jar it loose. */
2189 struct atimer *timer;
2190 EMACS_TIME offset;
2192 stop_polling ();
2193 EMACS_SET_SECS_USECS (offset, 1, 0);
2194 timer = start_atimer (ATIMER_RELATIVE, offset, create_process_1, 0);
2196 if (forkin >= 0)
2197 emacs_close (forkin);
2199 cancel_atimer (timer);
2200 start_polling ();
2203 if (forkin != forkout && forkout >= 0)
2204 emacs_close (forkout);
2206 #ifdef HAVE_PTYS
2207 if (pty_flag)
2208 XPROCESS (process)->tty_name = build_string (pty_name);
2209 else
2210 #endif
2211 XPROCESS (process)->tty_name = Qnil;
2213 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
2214 /* Wait for child_setup to complete in case that vfork is
2215 actually defined as fork. The descriptor wait_child_setup[1]
2216 of a pipe is closed at the child side either by close-on-exec
2217 on successful execvp or the _exit call in child_setup. */
2219 char dummy;
2221 emacs_close (wait_child_setup[1]);
2222 emacs_read (wait_child_setup[0], &dummy, 1);
2223 emacs_close (wait_child_setup[0]);
2225 #endif
2228 /* Restore the signal state whether vfork succeeded or not.
2229 (We will signal an error, below, if it failed.) */
2230 #ifdef POSIX_SIGNALS
2231 #ifdef HAVE_WORKING_VFORK
2232 /* Restore the parent's signal handlers. */
2233 sigaction (SIGINT, &sigint_action, 0);
2234 sigaction (SIGQUIT, &sigquit_action, 0);
2235 #ifdef AIX
2236 sigaction (SIGHUP, &sighup_action, 0);
2237 #endif
2238 #endif /* HAVE_WORKING_VFORK */
2239 /* Stop blocking signals in the parent. */
2240 sigprocmask (SIG_SETMASK, &procmask, 0);
2241 #else /* !POSIX_SIGNALS */
2242 #ifdef SIGCHLD
2243 #if defined (BSD_SYSTEM) || defined (HPUX)
2244 sigsetmask (SIGEMPTYMASK);
2245 #else /* ordinary USG */
2246 #if 0
2247 signal (SIGCHLD, sigchld);
2248 /* Now really handle any of these signals
2249 that came in during this function. */
2250 if (sigchld_deferred)
2251 kill (getpid (), SIGCHLD);
2252 #endif
2253 #endif /* ordinary USG */
2254 #endif /* SIGCHLD */
2255 #endif /* !POSIX_SIGNALS */
2257 /* Now generate the error if vfork failed. */
2258 if (pid < 0)
2259 report_file_error ("Doing vfork", Qnil);
2263 #ifdef HAVE_SOCKETS
2265 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2266 The address family of sa is not included in the result. */
2268 static Lisp_Object
2269 conv_sockaddr_to_lisp (sa, len)
2270 struct sockaddr *sa;
2271 int len;
2273 Lisp_Object address;
2274 int i;
2275 unsigned char *cp;
2276 register struct Lisp_Vector *p;
2278 /* Workaround for a bug in getsockname on BSD: Names bound to
2279 sockets in the UNIX domain are inaccessible; getsockname returns
2280 a zero length name. */
2281 if (len < OFFSETOF (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2282 return empty_unibyte_string;
2284 switch (sa->sa_family)
2286 case AF_INET:
2288 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2289 len = sizeof (sin->sin_addr) + 1;
2290 address = Fmake_vector (make_number (len), Qnil);
2291 p = XVECTOR (address);
2292 p->contents[--len] = make_number (ntohs (sin->sin_port));
2293 cp = (unsigned char *) &sin->sin_addr;
2294 break;
2296 #ifdef AF_INET6
2297 case AF_INET6:
2299 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2300 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2301 len = sizeof (sin6->sin6_addr)/2 + 1;
2302 address = Fmake_vector (make_number (len), Qnil);
2303 p = XVECTOR (address);
2304 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2305 for (i = 0; i < len; i++)
2306 p->contents[i] = make_number (ntohs (ip6[i]));
2307 return address;
2309 #endif
2310 #ifdef HAVE_LOCAL_SOCKETS
2311 case AF_LOCAL:
2313 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2314 for (i = 0; i < sizeof (sockun->sun_path); i++)
2315 if (sockun->sun_path[i] == 0)
2316 break;
2317 return make_unibyte_string (sockun->sun_path, i);
2319 #endif
2320 default:
2321 len -= OFFSETOF (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2322 address = Fcons (make_number (sa->sa_family),
2323 Fmake_vector (make_number (len), Qnil));
2324 p = XVECTOR (XCDR (address));
2325 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2326 break;
2329 i = 0;
2330 while (i < len)
2331 p->contents[i++] = make_number (*cp++);
2333 return address;
2337 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2339 static int
2340 get_lisp_to_sockaddr_size (address, familyp)
2341 Lisp_Object address;
2342 int *familyp;
2344 register struct Lisp_Vector *p;
2346 if (VECTORP (address))
2348 p = XVECTOR (address);
2349 if (p->size == 5)
2351 *familyp = AF_INET;
2352 return sizeof (struct sockaddr_in);
2354 #ifdef AF_INET6
2355 else if (p->size == 9)
2357 *familyp = AF_INET6;
2358 return sizeof (struct sockaddr_in6);
2360 #endif
2362 #ifdef HAVE_LOCAL_SOCKETS
2363 else if (STRINGP (address))
2365 *familyp = AF_LOCAL;
2366 return sizeof (struct sockaddr_un);
2368 #endif
2369 else if (CONSP (address) && INTEGERP (XCAR (address)) && VECTORP (XCDR (address)))
2371 struct sockaddr *sa;
2372 *familyp = XINT (XCAR (address));
2373 p = XVECTOR (XCDR (address));
2374 return p->size + sizeof (sa->sa_family);
2376 return 0;
2379 /* Convert an address object (vector or string) to an internal sockaddr.
2381 The address format has been basically validated by
2382 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2383 it could have come from user data. So if FAMILY is not valid,
2384 we return after zeroing *SA. */
2386 static void
2387 conv_lisp_to_sockaddr (family, address, sa, len)
2388 int family;
2389 Lisp_Object address;
2390 struct sockaddr *sa;
2391 int len;
2393 register struct Lisp_Vector *p;
2394 register unsigned char *cp = NULL;
2395 register int i;
2397 bzero (sa, len);
2399 if (VECTORP (address))
2401 p = XVECTOR (address);
2402 if (family == AF_INET)
2404 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2405 len = sizeof (sin->sin_addr) + 1;
2406 i = XINT (p->contents[--len]);
2407 sin->sin_port = htons (i);
2408 cp = (unsigned char *)&sin->sin_addr;
2409 sa->sa_family = family;
2411 #ifdef AF_INET6
2412 else if (family == AF_INET6)
2414 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2415 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2416 len = sizeof (sin6->sin6_addr) + 1;
2417 i = XINT (p->contents[--len]);
2418 sin6->sin6_port = htons (i);
2419 for (i = 0; i < len; i++)
2420 if (INTEGERP (p->contents[i]))
2422 int j = XFASTINT (p->contents[i]) & 0xffff;
2423 ip6[i] = ntohs (j);
2425 sa->sa_family = family;
2427 #endif
2428 return;
2430 else if (STRINGP (address))
2432 #ifdef HAVE_LOCAL_SOCKETS
2433 if (family == AF_LOCAL)
2435 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2436 cp = SDATA (address);
2437 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2438 sockun->sun_path[i] = *cp++;
2439 sa->sa_family = family;
2441 #endif
2442 return;
2444 else
2446 p = XVECTOR (XCDR (address));
2447 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2450 for (i = 0; i < len; i++)
2451 if (INTEGERP (p->contents[i]))
2452 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2455 #ifdef DATAGRAM_SOCKETS
2456 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2457 1, 1, 0,
2458 doc: /* Get the current datagram address associated with PROCESS. */)
2459 (process)
2460 Lisp_Object process;
2462 int channel;
2464 CHECK_PROCESS (process);
2466 if (!DATAGRAM_CONN_P (process))
2467 return Qnil;
2469 channel = XPROCESS (process)->infd;
2470 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2471 datagram_address[channel].len);
2474 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2475 2, 2, 0,
2476 doc: /* Set the datagram address for PROCESS to ADDRESS.
2477 Returns nil upon error setting address, ADDRESS otherwise. */)
2478 (process, address)
2479 Lisp_Object process, address;
2481 int channel;
2482 int family, len;
2484 CHECK_PROCESS (process);
2486 if (!DATAGRAM_CONN_P (process))
2487 return Qnil;
2489 channel = XPROCESS (process)->infd;
2491 len = get_lisp_to_sockaddr_size (address, &family);
2492 if (datagram_address[channel].len != len)
2493 return Qnil;
2494 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2495 return address;
2497 #endif
2500 static struct socket_options {
2501 /* The name of this option. Should be lowercase version of option
2502 name without SO_ prefix. */
2503 char *name;
2504 /* Option level SOL_... */
2505 int optlevel;
2506 /* Option number SO_... */
2507 int optnum;
2508 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2509 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2510 } socket_options[] =
2512 #ifdef SO_BINDTODEVICE
2513 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2514 #endif
2515 #ifdef SO_BROADCAST
2516 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2517 #endif
2518 #ifdef SO_DONTROUTE
2519 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2520 #endif
2521 #ifdef SO_KEEPALIVE
2522 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2523 #endif
2524 #ifdef SO_LINGER
2525 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2526 #endif
2527 #ifdef SO_OOBINLINE
2528 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2529 #endif
2530 #ifdef SO_PRIORITY
2531 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2532 #endif
2533 #ifdef SO_REUSEADDR
2534 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2535 #endif
2536 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2539 /* Set option OPT to value VAL on socket S.
2541 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2542 Signals an error if setting a known option fails.
2545 static int
2546 set_socket_option (s, opt, val)
2547 int s;
2548 Lisp_Object opt, val;
2550 char *name;
2551 struct socket_options *sopt;
2552 int ret = 0;
2554 CHECK_SYMBOL (opt);
2556 name = (char *) SDATA (SYMBOL_NAME (opt));
2557 for (sopt = socket_options; sopt->name; sopt++)
2558 if (strcmp (name, sopt->name) == 0)
2559 break;
2561 switch (sopt->opttype)
2563 case SOPT_BOOL:
2565 int optval;
2566 optval = NILP (val) ? 0 : 1;
2567 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2568 &optval, sizeof (optval));
2569 break;
2572 case SOPT_INT:
2574 int optval;
2575 if (INTEGERP (val))
2576 optval = XINT (val);
2577 else
2578 error ("Bad option value for %s", name);
2579 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2580 &optval, sizeof (optval));
2581 break;
2584 #ifdef SO_BINDTODEVICE
2585 case SOPT_IFNAME:
2587 char devname[IFNAMSIZ+1];
2589 /* This is broken, at least in the Linux 2.4 kernel.
2590 To unbind, the arg must be a zero integer, not the empty string.
2591 This should work on all systems. KFS. 2003-09-23. */
2592 bzero (devname, sizeof devname);
2593 if (STRINGP (val))
2595 char *arg = (char *) SDATA (val);
2596 int len = min (strlen (arg), IFNAMSIZ);
2597 bcopy (arg, devname, len);
2599 else if (!NILP (val))
2600 error ("Bad option value for %s", name);
2601 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2602 devname, IFNAMSIZ);
2603 break;
2605 #endif
2607 #ifdef SO_LINGER
2608 case SOPT_LINGER:
2610 struct linger linger;
2612 linger.l_onoff = 1;
2613 linger.l_linger = 0;
2614 if (INTEGERP (val))
2615 linger.l_linger = XINT (val);
2616 else
2617 linger.l_onoff = NILP (val) ? 0 : 1;
2618 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2619 &linger, sizeof (linger));
2620 break;
2622 #endif
2624 default:
2625 return 0;
2628 if (ret < 0)
2629 report_file_error ("Cannot set network option",
2630 Fcons (opt, Fcons (val, Qnil)));
2631 return (1 << sopt->optbit);
2635 DEFUN ("set-network-process-option",
2636 Fset_network_process_option, Sset_network_process_option,
2637 3, 4, 0,
2638 doc: /* For network process PROCESS set option OPTION to value VALUE.
2639 See `make-network-process' for a list of options and values.
2640 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2641 OPTION is not a supported option, return nil instead; otherwise return t. */)
2642 (process, option, value, no_error)
2643 Lisp_Object process, option, value;
2644 Lisp_Object no_error;
2646 int s;
2647 struct Lisp_Process *p;
2649 CHECK_PROCESS (process);
2650 p = XPROCESS (process);
2651 if (!NETCONN1_P (p))
2652 error ("Process is not a network process");
2654 s = p->infd;
2655 if (s < 0)
2656 error ("Process is not running");
2658 if (set_socket_option (s, option, value))
2660 p->childp = Fplist_put (p->childp, option, value);
2661 return Qt;
2664 if (NILP (no_error))
2665 error ("Unknown or unsupported option");
2667 return Qnil;
2671 #ifdef HAVE_SERIAL
2672 DEFUN ("serial-process-configure",
2673 Fserial_process_configure,
2674 Sserial_process_configure,
2675 0, MANY, 0,
2676 doc: /* Configure speed, bytesize, etc. of a serial process.
2678 Arguments are specified as keyword/argument pairs. Attributes that
2679 are not given are re-initialized from the process's current
2680 configuration (available via the function `process-contact') or set to
2681 reasonable default values. The following arguments are defined:
2683 :process PROCESS
2684 :name NAME
2685 :buffer BUFFER
2686 :port PORT
2687 -- Any of these arguments can be given to identify the process that is
2688 to be configured. If none of these arguments is given, the current
2689 buffer's process is used.
2691 :speed SPEED -- SPEED is the speed of the serial port in bits per
2692 second, also called baud rate. Any value can be given for SPEED, but
2693 most serial ports work only at a few defined values between 1200 and
2694 115200, with 9600 being the most common value. If SPEED is nil, the
2695 serial port is not configured any further, i.e., all other arguments
2696 are ignored. This may be useful for special serial ports such as
2697 Bluetooth-to-serial converters which can only be configured through AT
2698 commands. A value of nil for SPEED can be used only when passed
2699 through `make-serial-process' or `serial-term'.
2701 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2702 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2704 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2705 `odd' (use odd parity), or the symbol `even' (use even parity). If
2706 PARITY is not given, no parity is used.
2708 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2709 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2710 is not given or nil, 1 stopbit is used.
2712 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2713 flowcontrol to be used, which is either nil (don't use flowcontrol),
2714 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2715 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2716 flowcontrol is used.
2718 `serial-process-configure' is called by `make-serial-process' for the
2719 initial configuration of the serial port.
2721 Examples:
2723 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2725 \(serial-process-configure
2726 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2728 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2730 usage: (serial-process-configure &rest ARGS) */)
2731 (nargs, args)
2732 int nargs;
2733 Lisp_Object *args;
2735 struct Lisp_Process *p;
2736 Lisp_Object contact = Qnil;
2737 Lisp_Object proc = Qnil;
2738 struct gcpro gcpro1;
2740 contact = Flist (nargs, args);
2741 GCPRO1 (contact);
2743 proc = Fplist_get (contact, QCprocess);
2744 if (NILP (proc))
2745 proc = Fplist_get (contact, QCname);
2746 if (NILP (proc))
2747 proc = Fplist_get (contact, QCbuffer);
2748 if (NILP (proc))
2749 proc = Fplist_get (contact, QCport);
2750 proc = get_process (proc);
2751 p = XPROCESS (proc);
2752 if (!EQ (p->type, Qserial))
2753 error ("Not a serial process");
2755 if (NILP (Fplist_get (p->childp, QCspeed)))
2757 UNGCPRO;
2758 return Qnil;
2761 serial_configure (p, contact);
2763 UNGCPRO;
2764 return Qnil;
2767 /* Used by make-serial-process to recover from errors. */
2768 Lisp_Object make_serial_process_unwind (Lisp_Object proc)
2770 if (!PROCESSP (proc))
2771 abort ();
2772 remove_process (proc);
2773 return Qnil;
2776 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2777 0, MANY, 0,
2778 doc: /* Create and return a serial port process.
2780 In Emacs, serial port connections are represented by process objects,
2781 so input and output work as for subprocesses, and `delete-process'
2782 closes a serial port connection. However, a serial process has no
2783 process id, it cannot be signaled, and the status codes are different
2784 from normal processes.
2786 `make-serial-process' creates a process and a buffer, on which you
2787 probably want to use `process-send-string'. Try \\[serial-term] for
2788 an interactive terminal. See below for examples.
2790 Arguments are specified as keyword/argument pairs. The following
2791 arguments are defined:
2793 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2794 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2795 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2796 the backslashes in strings).
2798 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2799 which is called by `make-serial-process'.
2801 :name NAME -- NAME is the name of the process. If NAME is not given,
2802 the value of PORT is used.
2804 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2805 with the process. Process output goes at the end of that buffer,
2806 unless you specify an output stream or filter function to handle the
2807 output. If BUFFER is not given, the value of NAME is used.
2809 :coding CODING -- If CODING is a symbol, it specifies the coding
2810 system used for both reading and writing for this process. If CODING
2811 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2812 ENCODING is used for writing.
2814 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2815 the process is running. If BOOL is not given, query before exiting.
2817 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2818 In the stopped state, a serial process does not accept incoming data,
2819 but you can send outgoing data. The stopped state is cleared by
2820 `continue-process' and set by `stop-process'.
2822 :filter FILTER -- Install FILTER as the process filter.
2824 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2826 :plist PLIST -- Install PLIST as the initial plist of the process.
2828 :speed
2829 :bytesize
2830 :parity
2831 :stopbits
2832 :flowcontrol
2833 -- These arguments are handled by `serial-process-configure', which is
2834 called by `make-serial-process'.
2836 The original argument list, possibly modified by later configuration,
2837 is available via the function `process-contact'.
2839 Examples:
2841 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2843 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2845 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2847 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2849 usage: (make-serial-process &rest ARGS) */)
2850 (nargs, args)
2851 int nargs;
2852 Lisp_Object *args;
2854 int fd = -1;
2855 Lisp_Object proc, contact, port;
2856 struct Lisp_Process *p;
2857 struct gcpro gcpro1;
2858 Lisp_Object name, buffer;
2859 Lisp_Object tem, val;
2860 int specpdl_count = -1;
2862 if (nargs == 0)
2863 return Qnil;
2865 contact = Flist (nargs, args);
2866 GCPRO1 (contact);
2868 port = Fplist_get (contact, QCport);
2869 if (NILP (port))
2870 error ("No port specified");
2871 CHECK_STRING (port);
2873 if (NILP (Fplist_member (contact, QCspeed)))
2874 error (":speed not specified");
2875 if (!NILP (Fplist_get (contact, QCspeed)))
2876 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2878 name = Fplist_get (contact, QCname);
2879 if (NILP (name))
2880 name = port;
2881 CHECK_STRING (name);
2882 proc = make_process (name);
2883 specpdl_count = SPECPDL_INDEX ();
2884 record_unwind_protect (make_serial_process_unwind, proc);
2885 p = XPROCESS (proc);
2887 fd = serial_open ((char*) SDATA (port));
2888 p->infd = fd;
2889 p->outfd = fd;
2890 if (fd > max_process_desc)
2891 max_process_desc = fd;
2892 chan_process[fd] = proc;
2894 buffer = Fplist_get (contact, QCbuffer);
2895 if (NILP (buffer))
2896 buffer = name;
2897 buffer = Fget_buffer_create (buffer);
2898 p->buffer = buffer;
2900 p->childp = contact;
2901 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
2902 p->type = Qserial;
2903 p->sentinel = Fplist_get (contact, QCsentinel);
2904 p->filter = Fplist_get (contact, QCfilter);
2905 p->log = Qnil;
2906 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2907 p->kill_without_query = 1;
2908 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2909 p->command = Qt;
2910 p->pty_flag = 0;
2912 if (!EQ (p->command, Qt))
2914 FD_SET (fd, &input_wait_mask);
2915 FD_SET (fd, &non_keyboard_wait_mask);
2918 if (BUFFERP (buffer))
2920 set_marker_both (p->mark, buffer,
2921 BUF_ZV (XBUFFER (buffer)),
2922 BUF_ZV_BYTE (XBUFFER (buffer)));
2925 tem = Fplist_member (contact, QCcoding);
2926 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2927 tem = Qnil;
2929 val = Qnil;
2930 if (!NILP (tem))
2932 val = XCAR (XCDR (tem));
2933 if (CONSP (val))
2934 val = XCAR (val);
2936 else if (!NILP (Vcoding_system_for_read))
2937 val = Vcoding_system_for_read;
2938 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
2939 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
2940 val = Qnil;
2941 p->decode_coding_system = val;
2943 val = Qnil;
2944 if (!NILP (tem))
2946 val = XCAR (XCDR (tem));
2947 if (CONSP (val))
2948 val = XCDR (val);
2950 else if (!NILP (Vcoding_system_for_write))
2951 val = Vcoding_system_for_write;
2952 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
2953 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
2954 val = Qnil;
2955 p->encode_coding_system = val;
2957 setup_process_coding_systems (proc);
2958 p->decoding_buf = make_uninit_string (0);
2959 p->decoding_carryover = 0;
2960 p->encoding_buf = make_uninit_string (0);
2961 p->inherit_coding_system_flag
2962 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2964 Fserial_process_configure(nargs, args);
2966 specpdl_ptr = specpdl + specpdl_count;
2968 UNGCPRO;
2969 return proc;
2971 #endif /* HAVE_SERIAL */
2973 /* Create a network stream/datagram client/server process. Treated
2974 exactly like a normal process when reading and writing. Primary
2975 differences are in status display and process deletion. A network
2976 connection has no PID; you cannot signal it. All you can do is
2977 stop/continue it and deactivate/close it via delete-process */
2979 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2980 0, MANY, 0,
2981 doc: /* Create and return a network server or client process.
2983 In Emacs, network connections are represented by process objects, so
2984 input and output work as for subprocesses and `delete-process' closes
2985 a network connection. However, a network process has no process id,
2986 it cannot be signaled, and the status codes are different from normal
2987 processes.
2989 Arguments are specified as keyword/argument pairs. The following
2990 arguments are defined:
2992 :name NAME -- NAME is name for process. It is modified if necessary
2993 to make it unique.
2995 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2996 with the process. Process output goes at end of that buffer, unless
2997 you specify an output stream or filter function to handle the output.
2998 BUFFER may be also nil, meaning that this process is not associated
2999 with any buffer.
3001 :host HOST -- HOST is name of the host to connect to, or its IP
3002 address. The symbol `local' specifies the local host. If specified
3003 for a server process, it must be a valid name or address for the local
3004 host, and only clients connecting to that address will be accepted.
3006 :service SERVICE -- SERVICE is name of the service desired, or an
3007 integer specifying a port number to connect to. If SERVICE is t,
3008 a random port number is selected for the server. (If Emacs was
3009 compiled with getaddrinfo, a port number can also be specified as a
3010 string, e.g. "80", as well as an integer. This is not portable.)
3012 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3013 stream type connection, `datagram' creates a datagram type connection.
3015 :family FAMILY -- FAMILY is the address (and protocol) family for the
3016 service specified by HOST and SERVICE. The default (nil) is to use
3017 whatever address family (IPv4 or IPv6) that is defined for the host
3018 and port number specified by HOST and SERVICE. Other address families
3019 supported are:
3020 local -- for a local (i.e. UNIX) address specified by SERVICE.
3021 ipv4 -- use IPv4 address family only.
3022 ipv6 -- use IPv6 address family only.
3024 :local ADDRESS -- ADDRESS is the local address used for the connection.
3025 This parameter is ignored when opening a client process. When specified
3026 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3028 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3029 connection. This parameter is ignored when opening a stream server
3030 process. For a datagram server process, it specifies the initial
3031 setting of the remote datagram address. When specified for a client
3032 process, the FAMILY, HOST, and SERVICE args are ignored.
3034 The format of ADDRESS depends on the address family:
3035 - An IPv4 address is represented as an vector of integers [A B C D P]
3036 corresponding to numeric IP address A.B.C.D and port number P.
3037 - A local address is represented as a string with the address in the
3038 local address space.
3039 - An "unsupported family" address is represented by a cons (F . AV)
3040 where F is the family number and AV is a vector containing the socket
3041 address data with one element per address data byte. Do not rely on
3042 this format in portable code, as it may depend on implementation
3043 defined constants, data sizes, and data structure alignment.
3045 :coding CODING -- If CODING is a symbol, it specifies the coding
3046 system used for both reading and writing for this process. If CODING
3047 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3048 ENCODING is used for writing.
3050 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
3051 return without waiting for the connection to complete; instead, the
3052 sentinel function will be called with second arg matching "open" (if
3053 successful) or "failed" when the connect completes. Default is to use
3054 a blocking connect (i.e. wait) for stream type connections.
3056 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3057 running when Emacs is exited.
3059 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3060 In the stopped state, a server process does not accept new
3061 connections, and a client process does not handle incoming traffic.
3062 The stopped state is cleared by `continue-process' and set by
3063 `stop-process'.
3065 :filter FILTER -- Install FILTER as the process filter.
3067 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3068 process filter are multibyte, otherwise they are unibyte.
3069 If this keyword is not specified, the strings are multibyte if
3070 `default-enable-multibyte-characters' is non-nil.
3072 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3074 :log LOG -- Install LOG as the server process log function. This
3075 function is called when the server accepts a network connection from a
3076 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3077 is the server process, CLIENT is the new process for the connection,
3078 and MESSAGE is a string.
3080 :plist PLIST -- Install PLIST as the new process' initial plist.
3082 :server QLEN -- if QLEN is non-nil, create a server process for the
3083 specified FAMILY, SERVICE, and connection type (stream or datagram).
3084 If QLEN is an integer, it is used as the max. length of the server's
3085 pending connection queue (also known as the backlog); the default
3086 queue length is 5. Default is to create a client process.
3088 The following network options can be specified for this connection:
3090 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3091 :dontroute BOOL -- Only send to directly connected hosts.
3092 :keepalive BOOL -- Send keep-alive messages on network stream.
3093 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3094 :oobinline BOOL -- Place out-of-band data in receive data stream.
3095 :priority INT -- Set protocol defined priority for sent packets.
3096 :reuseaddr BOOL -- Allow reusing a recently used local address
3097 (this is allowed by default for a server process).
3098 :bindtodevice NAME -- bind to interface NAME. Using this may require
3099 special privileges on some systems.
3101 Consult the relevant system programmer's manual pages for more
3102 information on using these options.
3105 A server process will listen for and accept connections from clients.
3106 When a client connection is accepted, a new network process is created
3107 for the connection with the following parameters:
3109 - The client's process name is constructed by concatenating the server
3110 process' NAME and a client identification string.
3111 - If the FILTER argument is non-nil, the client process will not get a
3112 separate process buffer; otherwise, the client's process buffer is a newly
3113 created buffer named after the server process' BUFFER name or process
3114 NAME concatenated with the client identification string.
3115 - The connection type and the process filter and sentinel parameters are
3116 inherited from the server process' TYPE, FILTER and SENTINEL.
3117 - The client process' contact info is set according to the client's
3118 addressing information (typically an IP address and a port number).
3119 - The client process' plist is initialized from the server's plist.
3121 Notice that the FILTER and SENTINEL args are never used directly by
3122 the server process. Also, the BUFFER argument is not used directly by
3123 the server process, but via the optional :log function, accepted (and
3124 failed) connections may be logged in the server process' buffer.
3126 The original argument list, modified with the actual connection
3127 information, is available via the `process-contact' function.
3129 usage: (make-network-process &rest ARGS) */)
3130 (nargs, args)
3131 int nargs;
3132 Lisp_Object *args;
3134 Lisp_Object proc;
3135 Lisp_Object contact;
3136 struct Lisp_Process *p;
3137 #ifdef HAVE_GETADDRINFO
3138 struct addrinfo ai, *res, *lres;
3139 struct addrinfo hints;
3140 char *portstring, portbuf[128];
3141 #else /* HAVE_GETADDRINFO */
3142 struct _emacs_addrinfo
3144 int ai_family;
3145 int ai_socktype;
3146 int ai_protocol;
3147 int ai_addrlen;
3148 struct sockaddr *ai_addr;
3149 struct _emacs_addrinfo *ai_next;
3150 } ai, *res, *lres;
3151 #endif /* HAVE_GETADDRINFO */
3152 struct sockaddr_in address_in;
3153 #ifdef HAVE_LOCAL_SOCKETS
3154 struct sockaddr_un address_un;
3155 #endif
3156 int port;
3157 int ret = 0;
3158 int xerrno = 0;
3159 int s = -1, outch, inch;
3160 struct gcpro gcpro1;
3161 int count = SPECPDL_INDEX ();
3162 int count1;
3163 Lisp_Object QCaddress; /* one of QClocal or QCremote */
3164 Lisp_Object tem;
3165 Lisp_Object name, buffer, host, service, address;
3166 Lisp_Object filter, sentinel;
3167 int is_non_blocking_client = 0;
3168 int is_server = 0, backlog = 5;
3169 int socktype;
3170 int family = -1;
3172 if (nargs == 0)
3173 return Qnil;
3175 /* Save arguments for process-contact and clone-process. */
3176 contact = Flist (nargs, args);
3177 GCPRO1 (contact);
3179 #ifdef WINDOWSNT
3180 /* Ensure socket support is loaded if available. */
3181 init_winsock (TRUE);
3182 #endif
3184 /* :type TYPE (nil: stream, datagram */
3185 tem = Fplist_get (contact, QCtype);
3186 if (NILP (tem))
3187 socktype = SOCK_STREAM;
3188 #ifdef DATAGRAM_SOCKETS
3189 else if (EQ (tem, Qdatagram))
3190 socktype = SOCK_DGRAM;
3191 #endif
3192 else
3193 error ("Unsupported connection type");
3195 /* :server BOOL */
3196 tem = Fplist_get (contact, QCserver);
3197 if (!NILP (tem))
3199 /* Don't support network sockets when non-blocking mode is
3200 not available, since a blocked Emacs is not useful. */
3201 #if !defined(O_NONBLOCK) && !defined(O_NDELAY)
3202 error ("Network servers not supported");
3203 #else
3204 is_server = 1;
3205 if (INTEGERP (tem))
3206 backlog = XINT (tem);
3207 #endif
3210 /* Make QCaddress an alias for :local (server) or :remote (client). */
3211 QCaddress = is_server ? QClocal : QCremote;
3213 /* :nowait BOOL */
3214 if (!is_server && socktype == SOCK_STREAM
3215 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3217 #ifndef NON_BLOCKING_CONNECT
3218 error ("Non-blocking connect not supported");
3219 #else
3220 is_non_blocking_client = 1;
3221 #endif
3224 name = Fplist_get (contact, QCname);
3225 buffer = Fplist_get (contact, QCbuffer);
3226 filter = Fplist_get (contact, QCfilter);
3227 sentinel = Fplist_get (contact, QCsentinel);
3229 CHECK_STRING (name);
3231 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3232 ai.ai_socktype = socktype;
3233 ai.ai_protocol = 0;
3234 ai.ai_next = NULL;
3235 res = &ai;
3237 /* :local ADDRESS or :remote ADDRESS */
3238 address = Fplist_get (contact, QCaddress);
3239 if (!NILP (address))
3241 host = service = Qnil;
3243 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3244 error ("Malformed :address");
3245 ai.ai_family = family;
3246 ai.ai_addr = alloca (ai.ai_addrlen);
3247 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3248 goto open_socket;
3251 /* :family FAMILY -- nil (for Inet), local, or integer. */
3252 tem = Fplist_get (contact, QCfamily);
3253 if (NILP (tem))
3255 #if defined(HAVE_GETADDRINFO) && defined(AF_INET6)
3256 family = AF_UNSPEC;
3257 #else
3258 family = AF_INET;
3259 #endif
3261 #ifdef HAVE_LOCAL_SOCKETS
3262 else if (EQ (tem, Qlocal))
3263 family = AF_LOCAL;
3264 #endif
3265 #ifdef AF_INET6
3266 else if (EQ (tem, Qipv6))
3267 family = AF_INET6;
3268 #endif
3269 else if (EQ (tem, Qipv4))
3270 family = AF_INET;
3271 else if (INTEGERP (tem))
3272 family = XINT (tem);
3273 else
3274 error ("Unknown address family");
3276 ai.ai_family = family;
3278 /* :service SERVICE -- string, integer (port number), or t (random port). */
3279 service = Fplist_get (contact, QCservice);
3281 #ifdef HAVE_LOCAL_SOCKETS
3282 if (family == AF_LOCAL)
3284 /* Host is not used. */
3285 host = Qnil;
3286 CHECK_STRING (service);
3287 bzero (&address_un, sizeof address_un);
3288 address_un.sun_family = AF_LOCAL;
3289 strncpy (address_un.sun_path, SDATA (service), sizeof address_un.sun_path);
3290 ai.ai_addr = (struct sockaddr *) &address_un;
3291 ai.ai_addrlen = sizeof address_un;
3292 goto open_socket;
3294 #endif
3296 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3297 host = Fplist_get (contact, QChost);
3298 if (!NILP (host))
3300 if (EQ (host, Qlocal))
3301 host = build_string ("localhost");
3302 CHECK_STRING (host);
3305 /* Slow down polling to every ten seconds.
3306 Some kernels have a bug which causes retrying connect to fail
3307 after a connect. Polling can interfere with gethostbyname too. */
3308 #ifdef POLL_FOR_INPUT
3309 if (socktype == SOCK_STREAM)
3311 record_unwind_protect (unwind_stop_other_atimers, Qnil);
3312 bind_polling_period (10);
3314 #endif
3316 #ifdef HAVE_GETADDRINFO
3317 /* If we have a host, use getaddrinfo to resolve both host and service.
3318 Otherwise, use getservbyname to lookup the service. */
3319 if (!NILP (host))
3322 /* SERVICE can either be a string or int.
3323 Convert to a C string for later use by getaddrinfo. */
3324 if (EQ (service, Qt))
3325 portstring = "0";
3326 else if (INTEGERP (service))
3328 sprintf (portbuf, "%ld", (long) XINT (service));
3329 portstring = portbuf;
3331 else
3333 CHECK_STRING (service);
3334 portstring = SDATA (service);
3337 immediate_quit = 1;
3338 QUIT;
3339 memset (&hints, 0, sizeof (hints));
3340 hints.ai_flags = 0;
3341 hints.ai_family = family;
3342 hints.ai_socktype = socktype;
3343 hints.ai_protocol = 0;
3345 #ifdef HAVE_RES_INIT
3346 res_init ();
3347 #endif
3349 ret = getaddrinfo (SDATA (host), portstring, &hints, &res);
3350 if (ret)
3351 #ifdef HAVE_GAI_STRERROR
3352 error ("%s/%s %s", SDATA (host), portstring, gai_strerror(ret));
3353 #else
3354 error ("%s/%s getaddrinfo error %d", SDATA (host), portstring, ret);
3355 #endif
3356 immediate_quit = 0;
3358 goto open_socket;
3360 #endif /* HAVE_GETADDRINFO */
3362 /* We end up here if getaddrinfo is not defined, or in case no hostname
3363 has been specified (e.g. for a local server process). */
3365 if (EQ (service, Qt))
3366 port = 0;
3367 else if (INTEGERP (service))
3368 port = htons ((unsigned short) XINT (service));
3369 else
3371 struct servent *svc_info;
3372 CHECK_STRING (service);
3373 svc_info = getservbyname (SDATA (service),
3374 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3375 if (svc_info == 0)
3376 error ("Unknown service: %s", SDATA (service));
3377 port = svc_info->s_port;
3380 bzero (&address_in, sizeof address_in);
3381 address_in.sin_family = family;
3382 address_in.sin_addr.s_addr = INADDR_ANY;
3383 address_in.sin_port = port;
3385 #ifndef HAVE_GETADDRINFO
3386 if (!NILP (host))
3388 struct hostent *host_info_ptr;
3390 /* gethostbyname may fail with TRY_AGAIN, but we don't honour that,
3391 as it may `hang' Emacs for a very long time. */
3392 immediate_quit = 1;
3393 QUIT;
3395 #ifdef HAVE_RES_INIT
3396 res_init ();
3397 #endif
3399 host_info_ptr = gethostbyname (SDATA (host));
3400 immediate_quit = 0;
3402 if (host_info_ptr)
3404 bcopy (host_info_ptr->h_addr, (char *) &address_in.sin_addr,
3405 host_info_ptr->h_length);
3406 family = host_info_ptr->h_addrtype;
3407 address_in.sin_family = family;
3409 else
3410 /* Attempt to interpret host as numeric inet address */
3412 unsigned long numeric_addr;
3413 numeric_addr = inet_addr ((char *) SDATA (host));
3414 if (numeric_addr == -1)
3415 error ("Unknown host \"%s\"", SDATA (host));
3417 bcopy ((char *)&numeric_addr, (char *) &address_in.sin_addr,
3418 sizeof (address_in.sin_addr));
3422 #endif /* not HAVE_GETADDRINFO */
3424 ai.ai_family = family;
3425 ai.ai_addr = (struct sockaddr *) &address_in;
3426 ai.ai_addrlen = sizeof address_in;
3428 open_socket:
3430 /* Do this in case we never enter the for-loop below. */
3431 count1 = SPECPDL_INDEX ();
3432 s = -1;
3434 for (lres = res; lres; lres = lres->ai_next)
3436 int optn, optbits;
3438 retry_connect:
3440 s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
3441 if (s < 0)
3443 xerrno = errno;
3444 continue;
3447 #ifdef DATAGRAM_SOCKETS
3448 if (!is_server && socktype == SOCK_DGRAM)
3449 break;
3450 #endif /* DATAGRAM_SOCKETS */
3452 #ifdef NON_BLOCKING_CONNECT
3453 if (is_non_blocking_client)
3455 #ifdef O_NONBLOCK
3456 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3457 #else
3458 ret = fcntl (s, F_SETFL, O_NDELAY);
3459 #endif
3460 if (ret < 0)
3462 xerrno = errno;
3463 emacs_close (s);
3464 s = -1;
3465 continue;
3468 #endif
3470 /* Make us close S if quit. */
3471 record_unwind_protect (close_file_unwind, make_number (s));
3473 /* Parse network options in the arg list.
3474 We simply ignore anything which isn't a known option (including other keywords).
3475 An error is signaled if setting a known option fails. */
3476 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3477 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3479 if (is_server)
3481 /* Configure as a server socket. */
3483 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3484 explicit :reuseaddr key to override this. */
3485 #ifdef HAVE_LOCAL_SOCKETS
3486 if (family != AF_LOCAL)
3487 #endif
3488 if (!(optbits & (1 << OPIX_REUSEADDR)))
3490 int optval = 1;
3491 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3492 report_file_error ("Cannot set reuse option on server socket", Qnil);
3495 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3496 report_file_error ("Cannot bind server socket", Qnil);
3498 #ifdef HAVE_GETSOCKNAME
3499 if (EQ (service, Qt))
3501 struct sockaddr_in sa1;
3502 int len1 = sizeof (sa1);
3503 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3505 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3506 service = make_number (ntohs (sa1.sin_port));
3507 contact = Fplist_put (contact, QCservice, service);
3510 #endif
3512 if (socktype == SOCK_STREAM && listen (s, backlog))
3513 report_file_error ("Cannot listen on server socket", Qnil);
3515 break;
3518 immediate_quit = 1;
3519 QUIT;
3521 /* This turns off all alarm-based interrupts; the
3522 bind_polling_period call above doesn't always turn all the
3523 short-interval ones off, especially if interrupt_input is
3524 set.
3526 It'd be nice to be able to control the connect timeout
3527 though. Would non-blocking connect calls be portable?
3529 This used to be conditioned by HAVE_GETADDRINFO. Why? */
3531 turn_on_atimers (0);
3533 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3534 xerrno = errno;
3536 turn_on_atimers (1);
3538 if (ret == 0 || xerrno == EISCONN)
3540 /* The unwind-protect will be discarded afterwards.
3541 Likewise for immediate_quit. */
3542 break;
3545 #ifdef NON_BLOCKING_CONNECT
3546 #ifdef EINPROGRESS
3547 if (is_non_blocking_client && xerrno == EINPROGRESS)
3548 break;
3549 #else
3550 #ifdef EWOULDBLOCK
3551 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3552 break;
3553 #endif
3554 #endif
3555 #endif
3557 immediate_quit = 0;
3559 /* Discard the unwind protect closing S. */
3560 specpdl_ptr = specpdl + count1;
3561 emacs_close (s);
3562 s = -1;
3564 if (xerrno == EINTR)
3565 goto retry_connect;
3568 if (s >= 0)
3570 #ifdef DATAGRAM_SOCKETS
3571 if (socktype == SOCK_DGRAM)
3573 if (datagram_address[s].sa)
3574 abort ();
3575 datagram_address[s].sa = (struct sockaddr *) xmalloc (lres->ai_addrlen);
3576 datagram_address[s].len = lres->ai_addrlen;
3577 if (is_server)
3579 Lisp_Object remote;
3580 bzero (datagram_address[s].sa, lres->ai_addrlen);
3581 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3583 int rfamily, rlen;
3584 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3585 if (rfamily == lres->ai_family && rlen == lres->ai_addrlen)
3586 conv_lisp_to_sockaddr (rfamily, remote,
3587 datagram_address[s].sa, rlen);
3590 else
3591 bcopy (lres->ai_addr, datagram_address[s].sa, lres->ai_addrlen);
3593 #endif
3594 contact = Fplist_put (contact, QCaddress,
3595 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3596 #ifdef HAVE_GETSOCKNAME
3597 if (!is_server)
3599 struct sockaddr_in sa1;
3600 int len1 = sizeof (sa1);
3601 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3602 contact = Fplist_put (contact, QClocal,
3603 conv_sockaddr_to_lisp (&sa1, len1));
3605 #endif
3608 immediate_quit = 0;
3610 #ifdef HAVE_GETADDRINFO
3611 if (res != &ai)
3613 BLOCK_INPUT;
3614 freeaddrinfo (res);
3615 UNBLOCK_INPUT;
3617 #endif
3619 /* Discard the unwind protect for closing S, if any. */
3620 specpdl_ptr = specpdl + count1;
3622 /* Unwind bind_polling_period and request_sigio. */
3623 unbind_to (count, Qnil);
3625 if (s < 0)
3627 /* If non-blocking got this far - and failed - assume non-blocking is
3628 not supported after all. This is probably a wrong assumption, but
3629 the normal blocking calls to open-network-stream handles this error
3630 better. */
3631 if (is_non_blocking_client)
3632 return Qnil;
3634 errno = xerrno;
3635 if (is_server)
3636 report_file_error ("make server process failed", contact);
3637 else
3638 report_file_error ("make client process failed", contact);
3641 inch = s;
3642 outch = s;
3644 if (!NILP (buffer))
3645 buffer = Fget_buffer_create (buffer);
3646 proc = make_process (name);
3648 chan_process[inch] = proc;
3650 #ifdef O_NONBLOCK
3651 fcntl (inch, F_SETFL, O_NONBLOCK);
3652 #else
3653 #ifdef O_NDELAY
3654 fcntl (inch, F_SETFL, O_NDELAY);
3655 #endif
3656 #endif
3658 p = XPROCESS (proc);
3660 p->childp = contact;
3661 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
3662 p->type = Qnetwork;
3664 p->buffer = buffer;
3665 p->sentinel = sentinel;
3666 p->filter = filter;
3667 p->log = Fplist_get (contact, QClog);
3668 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3669 p->kill_without_query = 1;
3670 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3671 p->command = Qt;
3672 p->pid = 0;
3673 p->infd = inch;
3674 p->outfd = outch;
3675 if (is_server && socktype == SOCK_STREAM)
3676 p->status = Qlisten;
3678 /* Make the process marker point into the process buffer (if any). */
3679 if (BUFFERP (buffer))
3680 set_marker_both (p->mark, buffer,
3681 BUF_ZV (XBUFFER (buffer)),
3682 BUF_ZV_BYTE (XBUFFER (buffer)));
3684 #ifdef NON_BLOCKING_CONNECT
3685 if (is_non_blocking_client)
3687 /* We may get here if connect did succeed immediately. However,
3688 in that case, we still need to signal this like a non-blocking
3689 connection. */
3690 p->status = Qconnect;
3691 if (!FD_ISSET (inch, &connect_wait_mask))
3693 FD_SET (inch, &connect_wait_mask);
3694 num_pending_connects++;
3697 else
3698 #endif
3699 /* A server may have a client filter setting of Qt, but it must
3700 still listen for incoming connects unless it is stopped. */
3701 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3702 || (EQ (p->status, Qlisten) && NILP (p->command)))
3704 FD_SET (inch, &input_wait_mask);
3705 FD_SET (inch, &non_keyboard_wait_mask);
3708 if (inch > max_process_desc)
3709 max_process_desc = inch;
3711 tem = Fplist_member (contact, QCcoding);
3712 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3713 tem = Qnil; /* No error message (too late!). */
3716 /* Setup coding systems for communicating with the network stream. */
3717 struct gcpro gcpro1;
3718 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3719 Lisp_Object coding_systems = Qt;
3720 Lisp_Object args[5], val;
3722 if (!NILP (tem))
3724 val = XCAR (XCDR (tem));
3725 if (CONSP (val))
3726 val = XCAR (val);
3728 else if (!NILP (Vcoding_system_for_read))
3729 val = Vcoding_system_for_read;
3730 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
3731 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
3732 /* We dare not decode end-of-line format by setting VAL to
3733 Qraw_text, because the existing Emacs Lisp libraries
3734 assume that they receive bare code including a sequene of
3735 CR LF. */
3736 val = Qnil;
3737 else
3739 if (NILP (host) || NILP (service))
3740 coding_systems = Qnil;
3741 else
3743 args[0] = Qopen_network_stream, args[1] = name,
3744 args[2] = buffer, args[3] = host, args[4] = service;
3745 GCPRO1 (proc);
3746 coding_systems = Ffind_operation_coding_system (5, args);
3747 UNGCPRO;
3749 if (CONSP (coding_systems))
3750 val = XCAR (coding_systems);
3751 else if (CONSP (Vdefault_process_coding_system))
3752 val = XCAR (Vdefault_process_coding_system);
3753 else
3754 val = Qnil;
3756 p->decode_coding_system = val;
3758 if (!NILP (tem))
3760 val = XCAR (XCDR (tem));
3761 if (CONSP (val))
3762 val = XCDR (val);
3764 else if (!NILP (Vcoding_system_for_write))
3765 val = Vcoding_system_for_write;
3766 else if (NILP (current_buffer->enable_multibyte_characters))
3767 val = Qnil;
3768 else
3770 if (EQ (coding_systems, Qt))
3772 if (NILP (host) || NILP (service))
3773 coding_systems = Qnil;
3774 else
3776 args[0] = Qopen_network_stream, args[1] = name,
3777 args[2] = buffer, args[3] = host, args[4] = service;
3778 GCPRO1 (proc);
3779 coding_systems = Ffind_operation_coding_system (5, args);
3780 UNGCPRO;
3783 if (CONSP (coding_systems))
3784 val = XCDR (coding_systems);
3785 else if (CONSP (Vdefault_process_coding_system))
3786 val = XCDR (Vdefault_process_coding_system);
3787 else
3788 val = Qnil;
3790 p->encode_coding_system = val;
3792 setup_process_coding_systems (proc);
3794 p->decoding_buf = make_uninit_string (0);
3795 p->decoding_carryover = 0;
3796 p->encoding_buf = make_uninit_string (0);
3798 p->inherit_coding_system_flag
3799 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3801 UNGCPRO;
3802 return proc;
3804 #endif /* HAVE_SOCKETS */
3807 #if defined(HAVE_SOCKETS) && defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
3809 #ifdef SIOCGIFCONF
3810 DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3811 doc: /* Return an alist of all network interfaces and their network address.
3812 Each element is a cons, the car of which is a string containing the
3813 interface name, and the cdr is the network address in internal
3814 format; see the description of ADDRESS in `make-network-process'. */)
3817 struct ifconf ifconf;
3818 struct ifreq *ifreqs = NULL;
3819 int ifaces = 0;
3820 int buf_size, s;
3821 Lisp_Object res;
3823 s = socket (AF_INET, SOCK_STREAM, 0);
3824 if (s < 0)
3825 return Qnil;
3827 again:
3828 ifaces += 25;
3829 buf_size = ifaces * sizeof(ifreqs[0]);
3830 ifreqs = (struct ifreq *)xrealloc(ifreqs, buf_size);
3831 if (!ifreqs)
3833 close (s);
3834 return Qnil;
3837 ifconf.ifc_len = buf_size;
3838 ifconf.ifc_req = ifreqs;
3839 if (ioctl (s, SIOCGIFCONF, &ifconf))
3841 close (s);
3842 return Qnil;
3845 if (ifconf.ifc_len == buf_size)
3846 goto again;
3848 close (s);
3849 ifaces = ifconf.ifc_len / sizeof (ifreqs[0]);
3851 res = Qnil;
3852 while (--ifaces >= 0)
3854 struct ifreq *ifq = &ifreqs[ifaces];
3855 char namebuf[sizeof (ifq->ifr_name) + 1];
3856 if (ifq->ifr_addr.sa_family != AF_INET)
3857 continue;
3858 bcopy (ifq->ifr_name, namebuf, sizeof (ifq->ifr_name));
3859 namebuf[sizeof (ifq->ifr_name)] = 0;
3860 res = Fcons (Fcons (build_string (namebuf),
3861 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3862 sizeof (struct sockaddr))),
3863 res);
3866 return res;
3868 #endif /* SIOCGIFCONF */
3870 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
3872 struct ifflag_def {
3873 int flag_bit;
3874 char *flag_sym;
3877 static struct ifflag_def ifflag_table[] = {
3878 #ifdef IFF_UP
3879 { IFF_UP, "up" },
3880 #endif
3881 #ifdef IFF_BROADCAST
3882 { IFF_BROADCAST, "broadcast" },
3883 #endif
3884 #ifdef IFF_DEBUG
3885 { IFF_DEBUG, "debug" },
3886 #endif
3887 #ifdef IFF_LOOPBACK
3888 { IFF_LOOPBACK, "loopback" },
3889 #endif
3890 #ifdef IFF_POINTOPOINT
3891 { IFF_POINTOPOINT, "pointopoint" },
3892 #endif
3893 #ifdef IFF_RUNNING
3894 { IFF_RUNNING, "running" },
3895 #endif
3896 #ifdef IFF_NOARP
3897 { IFF_NOARP, "noarp" },
3898 #endif
3899 #ifdef IFF_PROMISC
3900 { IFF_PROMISC, "promisc" },
3901 #endif
3902 #ifdef IFF_NOTRAILERS
3903 { IFF_NOTRAILERS, "notrailers" },
3904 #endif
3905 #ifdef IFF_ALLMULTI
3906 { IFF_ALLMULTI, "allmulti" },
3907 #endif
3908 #ifdef IFF_MASTER
3909 { IFF_MASTER, "master" },
3910 #endif
3911 #ifdef IFF_SLAVE
3912 { IFF_SLAVE, "slave" },
3913 #endif
3914 #ifdef IFF_MULTICAST
3915 { IFF_MULTICAST, "multicast" },
3916 #endif
3917 #ifdef IFF_PORTSEL
3918 { IFF_PORTSEL, "portsel" },
3919 #endif
3920 #ifdef IFF_AUTOMEDIA
3921 { IFF_AUTOMEDIA, "automedia" },
3922 #endif
3923 #ifdef IFF_DYNAMIC
3924 { IFF_DYNAMIC, "dynamic" },
3925 #endif
3926 #ifdef IFF_OACTIVE
3927 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3928 #endif
3929 #ifdef IFF_SIMPLEX
3930 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3931 #endif
3932 #ifdef IFF_LINK0
3933 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3934 #endif
3935 #ifdef IFF_LINK1
3936 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3937 #endif
3938 #ifdef IFF_LINK2
3939 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3940 #endif
3941 { 0, 0 }
3944 DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
3945 doc: /* Return information about network interface named IFNAME.
3946 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3947 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3948 NETMASK is the layer 3 network mask, HWADDR is the layer 2 addres, and
3949 FLAGS is the current flags of the interface. */)
3950 (ifname)
3951 Lisp_Object ifname;
3953 struct ifreq rq;
3954 Lisp_Object res = Qnil;
3955 Lisp_Object elt;
3956 int s;
3957 int any = 0;
3959 CHECK_STRING (ifname);
3961 bzero (rq.ifr_name, sizeof rq.ifr_name);
3962 strncpy (rq.ifr_name, SDATA (ifname), sizeof (rq.ifr_name));
3964 s = socket (AF_INET, SOCK_STREAM, 0);
3965 if (s < 0)
3966 return Qnil;
3968 elt = Qnil;
3969 #if defined(SIOCGIFFLAGS) && defined(HAVE_STRUCT_IFREQ_IFR_FLAGS)
3970 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3972 int flags = rq.ifr_flags;
3973 struct ifflag_def *fp;
3974 int fnum;
3976 any++;
3977 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3979 if (flags & fp->flag_bit)
3981 elt = Fcons (intern (fp->flag_sym), elt);
3982 flags -= fp->flag_bit;
3985 for (fnum = 0; flags && fnum < 32; fnum++)
3987 if (flags & (1 << fnum))
3989 elt = Fcons (make_number (fnum), elt);
3993 #endif
3994 res = Fcons (elt, res);
3996 elt = Qnil;
3997 #if defined(SIOCGIFHWADDR) && defined(HAVE_STRUCT_IFREQ_IFR_HWADDR)
3998 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
4000 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4001 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4002 int n;
4004 any++;
4005 for (n = 0; n < 6; n++)
4006 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
4007 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
4009 #endif
4010 res = Fcons (elt, res);
4012 elt = Qnil;
4013 #if defined(SIOCGIFNETMASK) && (defined(HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined(HAVE_STRUCT_IFREQ_IFR_ADDR))
4014 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4016 any++;
4017 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4018 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4019 #else
4020 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4021 #endif
4023 #endif
4024 res = Fcons (elt, res);
4026 elt = Qnil;
4027 #if defined(SIOCGIFBRDADDR) && defined(HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4028 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4030 any++;
4031 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4033 #endif
4034 res = Fcons (elt, res);
4036 elt = Qnil;
4037 #if defined(SIOCGIFADDR) && defined(HAVE_STRUCT_IFREQ_IFR_ADDR)
4038 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4040 any++;
4041 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4043 #endif
4044 res = Fcons (elt, res);
4046 close (s);
4048 return any ? res : Qnil;
4050 #endif
4051 #endif /* HAVE_SOCKETS */
4053 /* Turn off input and output for process PROC. */
4055 void
4056 deactivate_process (proc)
4057 Lisp_Object proc;
4059 register int inchannel, outchannel;
4060 register struct Lisp_Process *p = XPROCESS (proc);
4062 inchannel = p->infd;
4063 outchannel = p->outfd;
4065 #ifdef ADAPTIVE_READ_BUFFERING
4066 if (p->read_output_delay > 0)
4068 if (--process_output_delay_count < 0)
4069 process_output_delay_count = 0;
4070 p->read_output_delay = 0;
4071 p->read_output_skip = 0;
4073 #endif
4075 if (inchannel >= 0)
4077 /* Beware SIGCHLD hereabouts. */
4078 flush_pending_output (inchannel);
4079 emacs_close (inchannel);
4080 if (outchannel >= 0 && outchannel != inchannel)
4081 emacs_close (outchannel);
4083 p->infd = -1;
4084 p->outfd = -1;
4085 #ifdef DATAGRAM_SOCKETS
4086 if (DATAGRAM_CHAN_P (inchannel))
4088 xfree (datagram_address[inchannel].sa);
4089 datagram_address[inchannel].sa = 0;
4090 datagram_address[inchannel].len = 0;
4092 #endif
4093 chan_process[inchannel] = Qnil;
4094 FD_CLR (inchannel, &input_wait_mask);
4095 FD_CLR (inchannel, &non_keyboard_wait_mask);
4096 #ifdef NON_BLOCKING_CONNECT
4097 if (FD_ISSET (inchannel, &connect_wait_mask))
4099 FD_CLR (inchannel, &connect_wait_mask);
4100 if (--num_pending_connects < 0)
4101 abort ();
4103 #endif
4104 if (inchannel == max_process_desc)
4106 int i;
4107 /* We just closed the highest-numbered process input descriptor,
4108 so recompute the highest-numbered one now. */
4109 max_process_desc = 0;
4110 for (i = 0; i < MAXDESC; i++)
4111 if (!NILP (chan_process[i]))
4112 max_process_desc = i;
4117 /* Close all descriptors currently in use for communication
4118 with subprocess. This is used in a newly-forked subprocess
4119 to get rid of irrelevant descriptors. */
4121 void
4122 close_process_descs ()
4124 #ifndef WINDOWSNT
4125 int i;
4126 for (i = 0; i < MAXDESC; i++)
4128 Lisp_Object process;
4129 process = chan_process[i];
4130 if (!NILP (process))
4132 int in = XPROCESS (process)->infd;
4133 int out = XPROCESS (process)->outfd;
4134 if (in >= 0)
4135 emacs_close (in);
4136 if (out >= 0 && in != out)
4137 emacs_close (out);
4140 #endif
4143 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4144 0, 4, 0,
4145 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4146 It is read into the process' buffers or given to their filter functions.
4147 Non-nil arg PROCESS means do not return until some output has been received
4148 from PROCESS.
4150 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
4151 and milliseconds to wait; return after that much time whether or not
4152 there is any subprocess output. If SECONDS is a floating point number,
4153 it specifies a fractional number of seconds to wait.
4154 The MILLISEC argument is obsolete and should be avoided.
4156 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
4157 from PROCESS, suspending reading output from other processes.
4158 If JUST-THIS-ONE is an integer, don't run any timers either.
4159 Return non-nil if we received any output before the timeout expired. */)
4160 (process, seconds, millisec, just_this_one)
4161 register Lisp_Object process, seconds, millisec, just_this_one;
4163 int secs, usecs = 0;
4165 if (! NILP (process))
4166 CHECK_PROCESS (process);
4167 else
4168 just_this_one = Qnil;
4170 if (!NILP (millisec))
4171 { /* Obsolete calling convention using integers rather than floats. */
4172 CHECK_NUMBER (millisec);
4173 if (NILP (seconds))
4174 seconds = make_float (XINT (millisec) / 1000.0);
4175 else
4177 CHECK_NUMBER (seconds);
4178 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4182 if (!NILP (seconds))
4184 if (INTEGERP (seconds))
4185 secs = XINT (seconds);
4186 else if (FLOATP (seconds))
4188 double timeout = XFLOAT_DATA (seconds);
4189 secs = (int) timeout;
4190 usecs = (int) ((timeout - (double) secs) * 1000000);
4192 else
4193 wrong_type_argument (Qnumberp, seconds);
4195 if (secs < 0 || (secs == 0 && usecs == 0))
4196 secs = -1, usecs = 0;
4198 else
4199 secs = NILP (process) ? -1 : 0;
4201 return
4202 (wait_reading_process_output (secs, usecs, 0, 0,
4203 Qnil,
4204 !NILP (process) ? XPROCESS (process) : NULL,
4205 NILP (just_this_one) ? 0 :
4206 !INTEGERP (just_this_one) ? 1 : -1)
4207 ? Qt : Qnil);
4210 /* Accept a connection for server process SERVER on CHANNEL. */
4212 static int connect_counter = 0;
4214 static void
4215 server_accept_connection (server, channel)
4216 Lisp_Object server;
4217 int channel;
4219 Lisp_Object proc, caller, name, buffer;
4220 Lisp_Object contact, host, service;
4221 struct Lisp_Process *ps= XPROCESS (server);
4222 struct Lisp_Process *p;
4223 int s;
4224 union u_sockaddr {
4225 struct sockaddr sa;
4226 struct sockaddr_in in;
4227 #ifdef AF_INET6
4228 struct sockaddr_in6 in6;
4229 #endif
4230 #ifdef HAVE_LOCAL_SOCKETS
4231 struct sockaddr_un un;
4232 #endif
4233 } saddr;
4234 int len = sizeof saddr;
4236 s = accept (channel, &saddr.sa, &len);
4238 if (s < 0)
4240 int code = errno;
4242 if (code == EAGAIN)
4243 return;
4244 #ifdef EWOULDBLOCK
4245 if (code == EWOULDBLOCK)
4246 return;
4247 #endif
4249 if (!NILP (ps->log))
4250 call3 (ps->log, server, Qnil,
4251 concat3 (build_string ("accept failed with code"),
4252 Fnumber_to_string (make_number (code)),
4253 build_string ("\n")));
4254 return;
4257 connect_counter++;
4259 /* Setup a new process to handle the connection. */
4261 /* Generate a unique identification of the caller, and build contact
4262 information for this process. */
4263 host = Qt;
4264 service = Qnil;
4265 switch (saddr.sa.sa_family)
4267 case AF_INET:
4269 Lisp_Object args[5];
4270 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4271 args[0] = build_string ("%d.%d.%d.%d");
4272 args[1] = make_number (*ip++);
4273 args[2] = make_number (*ip++);
4274 args[3] = make_number (*ip++);
4275 args[4] = make_number (*ip++);
4276 host = Fformat (5, args);
4277 service = make_number (ntohs (saddr.in.sin_port));
4279 args[0] = build_string (" <%s:%d>");
4280 args[1] = host;
4281 args[2] = service;
4282 caller = Fformat (3, args);
4284 break;
4286 #ifdef AF_INET6
4287 case AF_INET6:
4289 Lisp_Object args[9];
4290 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4291 int i;
4292 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4293 for (i = 0; i < 8; i++)
4294 args[i+1] = make_number (ntohs(ip6[i]));
4295 host = Fformat (9, args);
4296 service = make_number (ntohs (saddr.in.sin_port));
4298 args[0] = build_string (" <[%s]:%d>");
4299 args[1] = host;
4300 args[2] = service;
4301 caller = Fformat (3, args);
4303 break;
4304 #endif
4306 #ifdef HAVE_LOCAL_SOCKETS
4307 case AF_LOCAL:
4308 #endif
4309 default:
4310 caller = Fnumber_to_string (make_number (connect_counter));
4311 caller = concat3 (build_string (" <"), caller, build_string (">"));
4312 break;
4315 /* Create a new buffer name for this process if it doesn't have a
4316 filter. The new buffer name is based on the buffer name or
4317 process name of the server process concatenated with the caller
4318 identification. */
4320 if (!NILP (ps->filter) && !EQ (ps->filter, Qt))
4321 buffer = Qnil;
4322 else
4324 buffer = ps->buffer;
4325 if (!NILP (buffer))
4326 buffer = Fbuffer_name (buffer);
4327 else
4328 buffer = ps->name;
4329 if (!NILP (buffer))
4331 buffer = concat2 (buffer, caller);
4332 buffer = Fget_buffer_create (buffer);
4336 /* Generate a unique name for the new server process. Combine the
4337 server process name with the caller identification. */
4339 name = concat2 (ps->name, caller);
4340 proc = make_process (name);
4342 chan_process[s] = proc;
4344 #ifdef O_NONBLOCK
4345 fcntl (s, F_SETFL, O_NONBLOCK);
4346 #else
4347 #ifdef O_NDELAY
4348 fcntl (s, F_SETFL, O_NDELAY);
4349 #endif
4350 #endif
4352 p = XPROCESS (proc);
4354 /* Build new contact information for this setup. */
4355 contact = Fcopy_sequence (ps->childp);
4356 contact = Fplist_put (contact, QCserver, Qnil);
4357 contact = Fplist_put (contact, QChost, host);
4358 if (!NILP (service))
4359 contact = Fplist_put (contact, QCservice, service);
4360 contact = Fplist_put (contact, QCremote,
4361 conv_sockaddr_to_lisp (&saddr.sa, len));
4362 #ifdef HAVE_GETSOCKNAME
4363 len = sizeof saddr;
4364 if (getsockname (s, &saddr.sa, &len) == 0)
4365 contact = Fplist_put (contact, QClocal,
4366 conv_sockaddr_to_lisp (&saddr.sa, len));
4367 #endif
4369 p->childp = contact;
4370 p->plist = Fcopy_sequence (ps->plist);
4371 p->type = Qnetwork;
4373 p->buffer = buffer;
4374 p->sentinel = ps->sentinel;
4375 p->filter = ps->filter;
4376 p->command = Qnil;
4377 p->pid = 0;
4378 p->infd = s;
4379 p->outfd = s;
4380 p->status = Qrun;
4382 /* Client processes for accepted connections are not stopped initially. */
4383 if (!EQ (p->filter, Qt))
4385 FD_SET (s, &input_wait_mask);
4386 FD_SET (s, &non_keyboard_wait_mask);
4389 if (s > max_process_desc)
4390 max_process_desc = s;
4392 /* Setup coding system for new process based on server process.
4393 This seems to be the proper thing to do, as the coding system
4394 of the new process should reflect the settings at the time the
4395 server socket was opened; not the current settings. */
4397 p->decode_coding_system = ps->decode_coding_system;
4398 p->encode_coding_system = ps->encode_coding_system;
4399 setup_process_coding_systems (proc);
4401 p->decoding_buf = make_uninit_string (0);
4402 p->decoding_carryover = 0;
4403 p->encoding_buf = make_uninit_string (0);
4405 p->inherit_coding_system_flag
4406 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4408 if (!NILP (ps->log))
4409 call3 (ps->log, server, proc,
4410 concat3 (build_string ("accept from "),
4411 (STRINGP (host) ? host : build_string ("-")),
4412 build_string ("\n")));
4414 if (!NILP (p->sentinel))
4415 exec_sentinel (proc,
4416 concat3 (build_string ("open from "),
4417 (STRINGP (host) ? host : build_string ("-")),
4418 build_string ("\n")));
4421 /* This variable is different from waiting_for_input in keyboard.c.
4422 It is used to communicate to a lisp process-filter/sentinel (via the
4423 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4424 for user-input when that process-filter was called.
4425 waiting_for_input cannot be used as that is by definition 0 when
4426 lisp code is being evalled.
4427 This is also used in record_asynch_buffer_change.
4428 For that purpose, this must be 0
4429 when not inside wait_reading_process_output. */
4430 static int waiting_for_user_input_p;
4432 static Lisp_Object
4433 wait_reading_process_output_unwind (data)
4434 Lisp_Object data;
4436 waiting_for_user_input_p = XINT (data);
4437 return Qnil;
4440 /* This is here so breakpoints can be put on it. */
4441 static void
4442 wait_reading_process_output_1 ()
4446 /* Use a wrapper around select to work around a bug in gdb 5.3.
4447 Normally, the wrapper is optimzed away by inlining.
4449 If emacs is stopped inside select, the gdb backtrace doesn't
4450 show the function which called select, so it is practically
4451 impossible to step through wait_reading_process_output. */
4453 #ifndef select
4454 static INLINE int
4455 select_wrapper (n, rfd, wfd, xfd, tmo)
4456 int n;
4457 SELECT_TYPE *rfd, *wfd, *xfd;
4458 EMACS_TIME *tmo;
4460 return select (n, rfd, wfd, xfd, tmo);
4462 #define select select_wrapper
4463 #endif
4465 /* Read and dispose of subprocess output while waiting for timeout to
4466 elapse and/or keyboard input to be available.
4468 TIME_LIMIT is:
4469 timeout in seconds, or
4470 zero for no limit, or
4471 -1 means gobble data immediately available but don't wait for any.
4473 MICROSECS is:
4474 an additional duration to wait, measured in microseconds.
4475 If this is nonzero and time_limit is 0, then the timeout
4476 consists of MICROSECS only.
4478 READ_KBD is a lisp value:
4479 0 to ignore keyboard input, or
4480 1 to return when input is available, or
4481 -1 meaning caller will actually read the input, so don't throw to
4482 the quit handler, or
4484 DO_DISPLAY != 0 means redisplay should be done to show subprocess
4485 output that arrives.
4487 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4488 (and gobble terminal input into the buffer if any arrives).
4490 If WAIT_PROC is specified, wait until something arrives from that
4491 process. The return value is true if we read some input from
4492 that process.
4494 If JUST_WAIT_PROC is non-nil, handle only output from WAIT_PROC
4495 (suspending output from other processes). A negative value
4496 means don't run any timers either.
4498 If WAIT_PROC is specified, then the function returns true if we
4499 received input from that process before the timeout elapsed.
4500 Otherwise, return true if we received input from any process. */
4503 wait_reading_process_output (time_limit, microsecs, read_kbd, do_display,
4504 wait_for_cell, wait_proc, just_wait_proc)
4505 int time_limit, microsecs, read_kbd, do_display;
4506 Lisp_Object wait_for_cell;
4507 struct Lisp_Process *wait_proc;
4508 int just_wait_proc;
4510 register int channel, nfds;
4511 SELECT_TYPE Available;
4512 #ifdef NON_BLOCKING_CONNECT
4513 SELECT_TYPE Connecting;
4514 int check_connect;
4515 #endif
4516 int check_delay, no_avail;
4517 int xerrno;
4518 Lisp_Object proc;
4519 EMACS_TIME timeout, end_time;
4520 int wait_channel = -1;
4521 int got_some_input = 0;
4522 int count = SPECPDL_INDEX ();
4524 FD_ZERO (&Available);
4525 #ifdef NON_BLOCKING_CONNECT
4526 FD_ZERO (&Connecting);
4527 #endif
4529 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4530 if (wait_proc != NULL)
4531 wait_channel = wait_proc->infd;
4533 record_unwind_protect (wait_reading_process_output_unwind,
4534 make_number (waiting_for_user_input_p));
4535 waiting_for_user_input_p = read_kbd;
4537 /* Since we may need to wait several times,
4538 compute the absolute time to return at. */
4539 if (time_limit || microsecs)
4541 EMACS_GET_TIME (end_time);
4542 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
4543 EMACS_ADD_TIME (end_time, end_time, timeout);
4546 while (1)
4548 int timeout_reduced_for_timers = 0;
4550 /* If calling from keyboard input, do not quit
4551 since we want to return C-g as an input character.
4552 Otherwise, do pending quit if requested. */
4553 if (read_kbd >= 0)
4554 QUIT;
4555 #ifdef SYNC_INPUT
4556 else
4557 process_pending_signals ();
4558 #endif
4560 /* Exit now if the cell we're waiting for became non-nil. */
4561 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4562 break;
4564 /* Compute time from now till when time limit is up */
4565 /* Exit if already run out */
4566 if (time_limit == -1)
4568 /* -1 specified for timeout means
4569 gobble output available now
4570 but don't wait at all. */
4572 EMACS_SET_SECS_USECS (timeout, 0, 0);
4574 else if (time_limit || microsecs)
4576 EMACS_GET_TIME (timeout);
4577 EMACS_SUB_TIME (timeout, end_time, timeout);
4578 if (EMACS_TIME_NEG_P (timeout))
4579 break;
4581 else
4583 EMACS_SET_SECS_USECS (timeout, 100000, 0);
4586 /* Normally we run timers here.
4587 But not if wait_for_cell; in those cases,
4588 the wait is supposed to be short,
4589 and those callers cannot handle running arbitrary Lisp code here. */
4590 if (NILP (wait_for_cell)
4591 && just_wait_proc >= 0)
4593 EMACS_TIME timer_delay;
4597 int old_timers_run = timers_run;
4598 struct buffer *old_buffer = current_buffer;
4599 Lisp_Object old_window = selected_window;
4601 timer_delay = timer_check (1);
4603 /* If a timer has run, this might have changed buffers
4604 an alike. Make read_key_sequence aware of that. */
4605 if (timers_run != old_timers_run
4606 && (old_buffer != current_buffer
4607 || !EQ (old_window, selected_window))
4608 && waiting_for_user_input_p == -1)
4609 record_asynch_buffer_change ();
4611 if (timers_run != old_timers_run && do_display)
4612 /* We must retry, since a timer may have requeued itself
4613 and that could alter the time_delay. */
4614 redisplay_preserve_echo_area (9);
4615 else
4616 break;
4618 while (!detect_input_pending ());
4620 /* If there is unread keyboard input, also return. */
4621 if (read_kbd != 0
4622 && requeued_events_pending_p ())
4623 break;
4625 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
4627 EMACS_TIME difference;
4628 EMACS_SUB_TIME (difference, timer_delay, timeout);
4629 if (EMACS_TIME_NEG_P (difference))
4631 timeout = timer_delay;
4632 timeout_reduced_for_timers = 1;
4635 /* If time_limit is -1, we are not going to wait at all. */
4636 else if (time_limit != -1)
4638 /* This is so a breakpoint can be put here. */
4639 wait_reading_process_output_1 ();
4643 /* Cause C-g and alarm signals to take immediate action,
4644 and cause input available signals to zero out timeout.
4646 It is important that we do this before checking for process
4647 activity. If we get a SIGCHLD after the explicit checks for
4648 process activity, timeout is the only way we will know. */
4649 if (read_kbd < 0)
4650 set_waiting_for_input (&timeout);
4652 /* If status of something has changed, and no input is
4653 available, notify the user of the change right away. After
4654 this explicit check, we'll let the SIGCHLD handler zap
4655 timeout to get our attention. When Emacs is run
4656 interactively, only do this with a nonzero DO_DISPLAY
4657 argument, because status_notify triggers redisplay. */
4658 if (update_tick != process_tick
4659 && (do_display || noninteractive))
4661 SELECT_TYPE Atemp;
4662 #ifdef NON_BLOCKING_CONNECT
4663 SELECT_TYPE Ctemp;
4664 #endif
4666 Atemp = input_wait_mask;
4667 IF_NON_BLOCKING_CONNECT (Ctemp = connect_wait_mask);
4669 EMACS_SET_SECS_USECS (timeout, 0, 0);
4670 if ((select (max (max (max_process_desc, max_keyboard_desc),
4671 max_gpm_desc) + 1,
4672 &Atemp,
4673 #ifdef NON_BLOCKING_CONNECT
4674 (num_pending_connects > 0 ? &Ctemp : (SELECT_TYPE *)0),
4675 #else
4676 (SELECT_TYPE *)0,
4677 #endif
4678 (SELECT_TYPE *)0, &timeout)
4679 <= 0))
4681 /* It's okay for us to do this and then continue with
4682 the loop, since timeout has already been zeroed out. */
4683 clear_waiting_for_input ();
4684 status_notify (NULL);
4688 /* Don't wait for output from a non-running process. Just
4689 read whatever data has already been received. */
4690 if (wait_proc && wait_proc->raw_status_new)
4691 update_status (wait_proc);
4692 if (wait_proc
4693 && ! EQ (wait_proc->status, Qrun)
4694 && ! EQ (wait_proc->status, Qconnect))
4696 int nread, total_nread = 0;
4698 clear_waiting_for_input ();
4699 XSETPROCESS (proc, wait_proc);
4701 /* Read data from the process, until we exhaust it. */
4702 while (wait_proc->infd >= 0)
4704 nread = read_process_output (proc, wait_proc->infd);
4706 if (nread == 0)
4707 break;
4709 if (0 < nread)
4711 total_nread += nread;
4712 got_some_input = 1;
4714 #ifdef EIO
4715 else if (nread == -1 && EIO == errno)
4716 break;
4717 #endif
4718 #ifdef EAGAIN
4719 else if (nread == -1 && EAGAIN == errno)
4720 break;
4721 #endif
4722 #ifdef EWOULDBLOCK
4723 else if (nread == -1 && EWOULDBLOCK == errno)
4724 break;
4725 #endif
4727 if (total_nread > 0 && do_display)
4728 redisplay_preserve_echo_area (10);
4730 break;
4733 /* Wait till there is something to do */
4735 if (wait_proc && just_wait_proc)
4737 if (wait_proc->infd < 0) /* Terminated */
4738 break;
4739 FD_SET (wait_proc->infd, &Available);
4740 check_delay = 0;
4741 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4743 else if (!NILP (wait_for_cell))
4745 Available = non_process_wait_mask;
4746 check_delay = 0;
4747 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4749 else
4751 if (! read_kbd)
4752 Available = non_keyboard_wait_mask;
4753 else
4754 Available = input_wait_mask;
4755 IF_NON_BLOCKING_CONNECT (check_connect = (num_pending_connects > 0));
4756 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4759 /* If frame size has changed or the window is newly mapped,
4760 redisplay now, before we start to wait. There is a race
4761 condition here; if a SIGIO arrives between now and the select
4762 and indicates that a frame is trashed, the select may block
4763 displaying a trashed screen. */
4764 if (frame_garbaged && do_display)
4766 clear_waiting_for_input ();
4767 redisplay_preserve_echo_area (11);
4768 if (read_kbd < 0)
4769 set_waiting_for_input (&timeout);
4772 no_avail = 0;
4773 if (read_kbd && detect_input_pending ())
4775 nfds = 0;
4776 no_avail = 1;
4778 else
4780 #ifdef NON_BLOCKING_CONNECT
4781 if (check_connect)
4782 Connecting = connect_wait_mask;
4783 #endif
4785 #ifdef ADAPTIVE_READ_BUFFERING
4786 /* Set the timeout for adaptive read buffering if any
4787 process has non-zero read_output_skip and non-zero
4788 read_output_delay, and we are not reading output for a
4789 specific wait_channel. It is not executed if
4790 Vprocess_adaptive_read_buffering is nil. */
4791 if (process_output_skip && check_delay > 0)
4793 int usecs = EMACS_USECS (timeout);
4794 if (EMACS_SECS (timeout) > 0 || usecs > READ_OUTPUT_DELAY_MAX)
4795 usecs = READ_OUTPUT_DELAY_MAX;
4796 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4798 proc = chan_process[channel];
4799 if (NILP (proc))
4800 continue;
4801 /* Find minimum non-zero read_output_delay among the
4802 processes with non-zero read_output_skip. */
4803 if (XPROCESS (proc)->read_output_delay > 0)
4805 check_delay--;
4806 if (!XPROCESS (proc)->read_output_skip)
4807 continue;
4808 FD_CLR (channel, &Available);
4809 XPROCESS (proc)->read_output_skip = 0;
4810 if (XPROCESS (proc)->read_output_delay < usecs)
4811 usecs = XPROCESS (proc)->read_output_delay;
4814 EMACS_SET_SECS_USECS (timeout, 0, usecs);
4815 process_output_skip = 0;
4817 #endif
4818 #ifdef HAVE_NS
4819 nfds = ns_select
4820 #else
4821 nfds = select
4822 #endif
4823 (max (max (max_process_desc, max_keyboard_desc),
4824 max_gpm_desc) + 1,
4825 &Available,
4826 #ifdef NON_BLOCKING_CONNECT
4827 (check_connect ? &Connecting : (SELECT_TYPE *)0),
4828 #else
4829 (SELECT_TYPE *)0,
4830 #endif
4831 (SELECT_TYPE *)0, &timeout);
4834 xerrno = errno;
4836 /* Make C-g and alarm signals set flags again */
4837 clear_waiting_for_input ();
4839 /* If we woke up due to SIGWINCH, actually change size now. */
4840 do_pending_window_change (0);
4842 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
4843 /* We wanted the full specified time, so return now. */
4844 break;
4845 if (nfds < 0)
4847 if (xerrno == EINTR)
4848 no_avail = 1;
4849 else if (xerrno == EBADF)
4851 #ifdef AIX
4852 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
4853 the child's closure of the pts gives the parent a SIGHUP, and
4854 the ptc file descriptor is automatically closed,
4855 yielding EBADF here or at select() call above.
4856 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
4857 in m/ibmrt-aix.h), and here we just ignore the select error.
4858 Cleanup occurs c/o status_notify after SIGCLD. */
4859 no_avail = 1; /* Cannot depend on values returned */
4860 #else
4861 abort ();
4862 #endif
4864 else
4865 error ("select error: %s", emacs_strerror (xerrno));
4868 if (no_avail)
4870 FD_ZERO (&Available);
4871 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4874 #if 0 /* When polling is used, interrupt_input is 0,
4875 so get_input_pending should read the input.
4876 So this should not be needed. */
4877 /* If we are using polling for input,
4878 and we see input available, make it get read now.
4879 Otherwise it might not actually get read for a second.
4880 And on hpux, since we turn off polling in wait_reading_process_output,
4881 it might never get read at all if we don't spend much time
4882 outside of wait_reading_process_output. */
4883 if (read_kbd && interrupt_input
4884 && keyboard_bit_set (&Available)
4885 && input_polling_used ())
4886 kill (getpid (), SIGALRM);
4887 #endif
4889 /* Check for keyboard input */
4890 /* If there is any, return immediately
4891 to give it higher priority than subprocesses */
4893 if (read_kbd != 0)
4895 int old_timers_run = timers_run;
4896 struct buffer *old_buffer = current_buffer;
4897 Lisp_Object old_window = selected_window;
4898 int leave = 0;
4900 if (detect_input_pending_run_timers (do_display))
4902 swallow_events (do_display);
4903 if (detect_input_pending_run_timers (do_display))
4904 leave = 1;
4907 /* If a timer has run, this might have changed buffers
4908 an alike. Make read_key_sequence aware of that. */
4909 if (timers_run != old_timers_run
4910 && waiting_for_user_input_p == -1
4911 && (old_buffer != current_buffer
4912 || !EQ (old_window, selected_window)))
4913 record_asynch_buffer_change ();
4915 if (leave)
4916 break;
4919 /* If there is unread keyboard input, also return. */
4920 if (read_kbd != 0
4921 && requeued_events_pending_p ())
4922 break;
4924 /* If we are not checking for keyboard input now,
4925 do process events (but don't run any timers).
4926 This is so that X events will be processed.
4927 Otherwise they may have to wait until polling takes place.
4928 That would causes delays in pasting selections, for example.
4930 (We used to do this only if wait_for_cell.) */
4931 if (read_kbd == 0 && detect_input_pending ())
4933 swallow_events (do_display);
4934 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4935 if (detect_input_pending ())
4936 break;
4937 #endif
4940 /* Exit now if the cell we're waiting for became non-nil. */
4941 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4942 break;
4944 #ifdef SIGIO
4945 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4946 go read it. This can happen with X on BSD after logging out.
4947 In that case, there really is no input and no SIGIO,
4948 but select says there is input. */
4950 if (read_kbd && interrupt_input
4951 && keyboard_bit_set (&Available) && ! noninteractive)
4952 kill (getpid (), SIGIO);
4953 #endif
4955 if (! wait_proc)
4956 got_some_input |= nfds > 0;
4958 /* If checking input just got us a size-change event from X,
4959 obey it now if we should. */
4960 if (read_kbd || ! NILP (wait_for_cell))
4961 do_pending_window_change (0);
4963 /* Check for data from a process. */
4964 if (no_avail || nfds == 0)
4965 continue;
4967 /* Really FIRST_PROC_DESC should be 0 on Unix,
4968 but this is safer in the short run. */
4969 for (channel = 0; channel <= max_process_desc; channel++)
4971 if (FD_ISSET (channel, &Available)
4972 && FD_ISSET (channel, &non_keyboard_wait_mask))
4974 int nread;
4976 /* If waiting for this channel, arrange to return as
4977 soon as no more input to be processed. No more
4978 waiting. */
4979 if (wait_channel == channel)
4981 wait_channel = -1;
4982 time_limit = -1;
4983 got_some_input = 1;
4985 proc = chan_process[channel];
4986 if (NILP (proc))
4987 continue;
4989 /* If this is a server stream socket, accept connection. */
4990 if (EQ (XPROCESS (proc)->status, Qlisten))
4992 server_accept_connection (proc, channel);
4993 continue;
4996 /* Read data from the process, starting with our
4997 buffered-ahead character if we have one. */
4999 nread = read_process_output (proc, channel);
5000 if (nread > 0)
5002 /* Since read_process_output can run a filter,
5003 which can call accept-process-output,
5004 don't try to read from any other processes
5005 before doing the select again. */
5006 FD_ZERO (&Available);
5008 if (do_display)
5009 redisplay_preserve_echo_area (12);
5011 #ifdef EWOULDBLOCK
5012 else if (nread == -1 && errno == EWOULDBLOCK)
5014 #endif
5015 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
5016 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
5017 #ifdef O_NONBLOCK
5018 else if (nread == -1 && errno == EAGAIN)
5020 #else
5021 #ifdef O_NDELAY
5022 else if (nread == -1 && errno == EAGAIN)
5024 /* Note that we cannot distinguish between no input
5025 available now and a closed pipe.
5026 With luck, a closed pipe will be accompanied by
5027 subprocess termination and SIGCHLD. */
5028 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
5030 #endif /* O_NDELAY */
5031 #endif /* O_NONBLOCK */
5032 #ifdef HAVE_PTYS
5033 /* On some OSs with ptys, when the process on one end of
5034 a pty exits, the other end gets an error reading with
5035 errno = EIO instead of getting an EOF (0 bytes read).
5036 Therefore, if we get an error reading and errno =
5037 EIO, just continue, because the child process has
5038 exited and should clean itself up soon (e.g. when we
5039 get a SIGCHLD).
5041 However, it has been known to happen that the SIGCHLD
5042 got lost. So raise the signal again just in case.
5043 It can't hurt. */
5044 else if (nread == -1 && errno == EIO)
5046 /* Clear the descriptor now, so we only raise the signal once. */
5047 FD_CLR (channel, &input_wait_mask);
5048 FD_CLR (channel, &non_keyboard_wait_mask);
5050 kill (getpid (), SIGCHLD);
5052 #endif /* HAVE_PTYS */
5053 /* If we can detect process termination, don't consider the process
5054 gone just because its pipe is closed. */
5055 #ifdef SIGCHLD
5056 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
5058 #endif
5059 else
5061 /* Preserve status of processes already terminated. */
5062 XPROCESS (proc)->tick = ++process_tick;
5063 deactivate_process (proc);
5064 if (XPROCESS (proc)->raw_status_new)
5065 update_status (XPROCESS (proc));
5066 if (EQ (XPROCESS (proc)->status, Qrun))
5067 XPROCESS (proc)->status
5068 = Fcons (Qexit, Fcons (make_number (256), Qnil));
5071 #ifdef NON_BLOCKING_CONNECT
5072 if (check_connect && FD_ISSET (channel, &Connecting)
5073 && FD_ISSET (channel, &connect_wait_mask))
5075 struct Lisp_Process *p;
5077 FD_CLR (channel, &connect_wait_mask);
5078 if (--num_pending_connects < 0)
5079 abort ();
5081 proc = chan_process[channel];
5082 if (NILP (proc))
5083 continue;
5085 p = XPROCESS (proc);
5087 #ifdef GNU_LINUX
5088 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5089 So only use it on systems where it is known to work. */
5091 int xlen = sizeof(xerrno);
5092 if (getsockopt(channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5093 xerrno = errno;
5095 #else
5097 struct sockaddr pname;
5098 int pnamelen = sizeof(pname);
5100 /* If connection failed, getpeername will fail. */
5101 xerrno = 0;
5102 if (getpeername(channel, &pname, &pnamelen) < 0)
5104 /* Obtain connect failure code through error slippage. */
5105 char dummy;
5106 xerrno = errno;
5107 if (errno == ENOTCONN && read(channel, &dummy, 1) < 0)
5108 xerrno = errno;
5111 #endif
5112 if (xerrno)
5114 p->tick = ++process_tick;
5115 p->status = Fcons (Qfailed, Fcons (make_number (xerrno), Qnil));
5116 deactivate_process (proc);
5118 else
5120 p->status = Qrun;
5121 /* Execute the sentinel here. If we had relied on
5122 status_notify to do it later, it will read input
5123 from the process before calling the sentinel. */
5124 exec_sentinel (proc, build_string ("open\n"));
5125 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
5127 FD_SET (p->infd, &input_wait_mask);
5128 FD_SET (p->infd, &non_keyboard_wait_mask);
5132 #endif /* NON_BLOCKING_CONNECT */
5133 } /* end for each file descriptor */
5134 } /* end while exit conditions not met */
5136 unbind_to (count, Qnil);
5138 /* If calling from keyboard input, do not quit
5139 since we want to return C-g as an input character.
5140 Otherwise, do pending quit if requested. */
5141 if (read_kbd >= 0)
5143 /* Prevent input_pending from remaining set if we quit. */
5144 clear_input_pending ();
5145 QUIT;
5148 return got_some_input;
5151 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5153 static Lisp_Object
5154 read_process_output_call (fun_and_args)
5155 Lisp_Object fun_and_args;
5157 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5160 static Lisp_Object
5161 read_process_output_error_handler (error)
5162 Lisp_Object error;
5164 cmd_error_internal (error, "error in process filter: ");
5165 Vinhibit_quit = Qt;
5166 update_echo_area ();
5167 Fsleep_for (make_number (2), Qnil);
5168 return Qt;
5171 /* Read pending output from the process channel,
5172 starting with our buffered-ahead character if we have one.
5173 Yield number of decoded characters read.
5175 This function reads at most 4096 characters.
5176 If you want to read all available subprocess output,
5177 you must call it repeatedly until it returns zero.
5179 The characters read are decoded according to PROC's coding-system
5180 for decoding. */
5182 static int
5183 read_process_output (proc, channel)
5184 Lisp_Object proc;
5185 register int channel;
5187 register int nbytes;
5188 char *chars;
5189 register Lisp_Object outstream;
5190 register struct Lisp_Process *p = XPROCESS (proc);
5191 register int opoint;
5192 struct coding_system *coding = proc_decode_coding_system[channel];
5193 int carryover = p->decoding_carryover;
5194 int readmax = 4096;
5196 chars = (char *) alloca (carryover + readmax);
5197 if (carryover)
5198 /* See the comment above. */
5199 bcopy (SDATA (p->decoding_buf), chars, carryover);
5201 #ifdef DATAGRAM_SOCKETS
5202 /* We have a working select, so proc_buffered_char is always -1. */
5203 if (DATAGRAM_CHAN_P (channel))
5205 int len = datagram_address[channel].len;
5206 nbytes = recvfrom (channel, chars + carryover, readmax,
5207 0, datagram_address[channel].sa, &len);
5209 else
5210 #endif
5211 if (proc_buffered_char[channel] < 0)
5213 nbytes = emacs_read (channel, chars + carryover, readmax);
5214 #ifdef ADAPTIVE_READ_BUFFERING
5215 if (nbytes > 0 && p->adaptive_read_buffering)
5217 int delay = p->read_output_delay;
5218 if (nbytes < 256)
5220 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5222 if (delay == 0)
5223 process_output_delay_count++;
5224 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5227 else if (delay > 0 && (nbytes == readmax))
5229 delay -= READ_OUTPUT_DELAY_INCREMENT;
5230 if (delay == 0)
5231 process_output_delay_count--;
5233 p->read_output_delay = delay;
5234 if (delay)
5236 p->read_output_skip = 1;
5237 process_output_skip = 1;
5240 #endif
5242 else
5244 chars[carryover] = proc_buffered_char[channel];
5245 proc_buffered_char[channel] = -1;
5246 nbytes = emacs_read (channel, chars + carryover + 1, readmax - 1);
5247 if (nbytes < 0)
5248 nbytes = 1;
5249 else
5250 nbytes = nbytes + 1;
5253 p->decoding_carryover = 0;
5255 /* At this point, NBYTES holds number of bytes just received
5256 (including the one in proc_buffered_char[channel]). */
5257 if (nbytes <= 0)
5259 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5260 return nbytes;
5261 coding->mode |= CODING_MODE_LAST_BLOCK;
5264 /* Now set NBYTES how many bytes we must decode. */
5265 nbytes += carryover;
5267 /* Read and dispose of the process output. */
5268 outstream = p->filter;
5269 if (!NILP (outstream))
5271 /* We inhibit quit here instead of just catching it so that
5272 hitting ^G when a filter happens to be running won't screw
5273 it up. */
5274 int count = SPECPDL_INDEX ();
5275 Lisp_Object odeactivate;
5276 Lisp_Object obuffer, okeymap;
5277 Lisp_Object text;
5278 int outer_running_asynch_code = running_asynch_code;
5279 int waiting = waiting_for_user_input_p;
5281 /* No need to gcpro these, because all we do with them later
5282 is test them for EQness, and none of them should be a string. */
5283 odeactivate = Vdeactivate_mark;
5284 XSETBUFFER (obuffer, current_buffer);
5285 okeymap = current_buffer->keymap;
5287 specbind (Qinhibit_quit, Qt);
5288 specbind (Qlast_nonmenu_event, Qt);
5290 /* In case we get recursively called,
5291 and we already saved the match data nonrecursively,
5292 save the same match data in safely recursive fashion. */
5293 if (outer_running_asynch_code)
5295 Lisp_Object tem;
5296 /* Don't clobber the CURRENT match data, either! */
5297 tem = Fmatch_data (Qnil, Qnil, Qnil);
5298 restore_search_regs ();
5299 record_unwind_save_match_data ();
5300 Fset_match_data (tem, Qt);
5303 /* For speed, if a search happens within this code,
5304 save the match data in a special nonrecursive fashion. */
5305 running_asynch_code = 1;
5307 decode_coding_c_string (coding, chars, nbytes, Qt);
5308 text = coding->dst_object;
5309 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5310 /* A new coding system might be found. */
5311 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5313 p->decode_coding_system = Vlast_coding_system_used;
5315 /* Don't call setup_coding_system for
5316 proc_decode_coding_system[channel] here. It is done in
5317 detect_coding called via decode_coding above. */
5319 /* If a coding system for encoding is not yet decided, we set
5320 it as the same as coding-system for decoding.
5322 But, before doing that we must check if
5323 proc_encode_coding_system[p->outfd] surely points to a
5324 valid memory because p->outfd will be changed once EOF is
5325 sent to the process. */
5326 if (NILP (p->encode_coding_system)
5327 && proc_encode_coding_system[p->outfd])
5329 p->encode_coding_system
5330 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5331 setup_coding_system (p->encode_coding_system,
5332 proc_encode_coding_system[p->outfd]);
5336 if (coding->carryover_bytes > 0)
5338 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5339 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5340 bcopy (coding->carryover, SDATA (p->decoding_buf),
5341 coding->carryover_bytes);
5342 p->decoding_carryover = coding->carryover_bytes;
5344 if (SBYTES (text) > 0)
5345 internal_condition_case_1 (read_process_output_call,
5346 Fcons (outstream,
5347 Fcons (proc, Fcons (text, Qnil))),
5348 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5349 read_process_output_error_handler);
5351 /* If we saved the match data nonrecursively, restore it now. */
5352 restore_search_regs ();
5353 running_asynch_code = outer_running_asynch_code;
5355 /* Handling the process output should not deactivate the mark. */
5356 Vdeactivate_mark = odeactivate;
5358 /* Restore waiting_for_user_input_p as it was
5359 when we were called, in case the filter clobbered it. */
5360 waiting_for_user_input_p = waiting;
5362 #if 0 /* Call record_asynch_buffer_change unconditionally,
5363 because we might have changed minor modes or other things
5364 that affect key bindings. */
5365 if (! EQ (Fcurrent_buffer (), obuffer)
5366 || ! EQ (current_buffer->keymap, okeymap))
5367 #endif
5368 /* But do it only if the caller is actually going to read events.
5369 Otherwise there's no need to make him wake up, and it could
5370 cause trouble (for example it would make sit_for return). */
5371 if (waiting_for_user_input_p == -1)
5372 record_asynch_buffer_change ();
5374 unbind_to (count, Qnil);
5375 return nbytes;
5378 /* If no filter, write into buffer if it isn't dead. */
5379 if (!NILP (p->buffer) && !NILP (XBUFFER (p->buffer)->name))
5381 Lisp_Object old_read_only;
5382 int old_begv, old_zv;
5383 int old_begv_byte, old_zv_byte;
5384 Lisp_Object odeactivate;
5385 int before, before_byte;
5386 int opoint_byte;
5387 Lisp_Object text;
5388 struct buffer *b;
5389 int count = SPECPDL_INDEX ();
5391 odeactivate = Vdeactivate_mark;
5393 record_unwind_protect (Fset_buffer, Fcurrent_buffer ());
5394 Fset_buffer (p->buffer);
5395 opoint = PT;
5396 opoint_byte = PT_BYTE;
5397 old_read_only = current_buffer->read_only;
5398 old_begv = BEGV;
5399 old_zv = ZV;
5400 old_begv_byte = BEGV_BYTE;
5401 old_zv_byte = ZV_BYTE;
5403 current_buffer->read_only = Qnil;
5405 /* Insert new output into buffer
5406 at the current end-of-output marker,
5407 thus preserving logical ordering of input and output. */
5408 if (XMARKER (p->mark)->buffer)
5409 SET_PT_BOTH (clip_to_bounds (BEGV, marker_position (p->mark), ZV),
5410 clip_to_bounds (BEGV_BYTE, marker_byte_position (p->mark),
5411 ZV_BYTE));
5412 else
5413 SET_PT_BOTH (ZV, ZV_BYTE);
5414 before = PT;
5415 before_byte = PT_BYTE;
5417 /* If the output marker is outside of the visible region, save
5418 the restriction and widen. */
5419 if (! (BEGV <= PT && PT <= ZV))
5420 Fwiden ();
5422 decode_coding_c_string (coding, chars, nbytes, Qt);
5423 text = coding->dst_object;
5424 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5425 /* A new coding system might be found. See the comment in the
5426 similar code in the previous `if' block. */
5427 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5429 p->decode_coding_system = Vlast_coding_system_used;
5430 if (NILP (p->encode_coding_system)
5431 && proc_encode_coding_system[p->outfd])
5433 p->encode_coding_system
5434 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5435 setup_coding_system (p->encode_coding_system,
5436 proc_encode_coding_system[p->outfd]);
5439 if (coding->carryover_bytes > 0)
5441 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5442 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5443 bcopy (coding->carryover, SDATA (p->decoding_buf),
5444 coding->carryover_bytes);
5445 p->decoding_carryover = coding->carryover_bytes;
5447 /* Adjust the multibyteness of TEXT to that of the buffer. */
5448 if (NILP (current_buffer->enable_multibyte_characters)
5449 != ! STRING_MULTIBYTE (text))
5450 text = (STRING_MULTIBYTE (text)
5451 ? Fstring_as_unibyte (text)
5452 : Fstring_to_multibyte (text));
5453 /* Insert before markers in case we are inserting where
5454 the buffer's mark is, and the user's next command is Meta-y. */
5455 insert_from_string_before_markers (text, 0, 0,
5456 SCHARS (text), SBYTES (text), 0);
5458 /* Make sure the process marker's position is valid when the
5459 process buffer is changed in the signal_after_change above.
5460 W3 is known to do that. */
5461 if (BUFFERP (p->buffer)
5462 && (b = XBUFFER (p->buffer), b != current_buffer))
5463 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5464 else
5465 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5467 update_mode_lines++;
5469 /* Make sure opoint and the old restrictions
5470 float ahead of any new text just as point would. */
5471 if (opoint >= before)
5473 opoint += PT - before;
5474 opoint_byte += PT_BYTE - before_byte;
5476 if (old_begv > before)
5478 old_begv += PT - before;
5479 old_begv_byte += PT_BYTE - before_byte;
5481 if (old_zv >= before)
5483 old_zv += PT - before;
5484 old_zv_byte += PT_BYTE - before_byte;
5487 /* If the restriction isn't what it should be, set it. */
5488 if (old_begv != BEGV || old_zv != ZV)
5489 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5491 /* Handling the process output should not deactivate the mark. */
5492 Vdeactivate_mark = odeactivate;
5494 current_buffer->read_only = old_read_only;
5495 SET_PT_BOTH (opoint, opoint_byte);
5496 unbind_to (count, Qnil);
5498 return nbytes;
5501 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p, Swaiting_for_user_input_p,
5502 0, 0, 0,
5503 doc: /* Returns non-nil if Emacs is waiting for input from the user.
5504 This is intended for use by asynchronous process output filters and sentinels. */)
5507 return (waiting_for_user_input_p ? Qt : Qnil);
5510 /* Sending data to subprocess */
5512 jmp_buf send_process_frame;
5513 Lisp_Object process_sent_to;
5515 SIGTYPE
5516 send_process_trap ()
5518 SIGNAL_THREAD_CHECK (SIGPIPE);
5519 sigunblock (sigmask (SIGPIPE));
5520 longjmp (send_process_frame, 1);
5523 /* Send some data to process PROC.
5524 BUF is the beginning of the data; LEN is the number of characters.
5525 OBJECT is the Lisp object that the data comes from. If OBJECT is
5526 nil or t, it means that the data comes from C string.
5528 If OBJECT is not nil, the data is encoded by PROC's coding-system
5529 for encoding before it is sent.
5531 This function can evaluate Lisp code and can garbage collect. */
5533 static void
5534 send_process (proc, buf, len, object)
5535 volatile Lisp_Object proc;
5536 unsigned char *volatile buf;
5537 volatile int len;
5538 volatile Lisp_Object object;
5540 /* Use volatile to protect variables from being clobbered by longjmp. */
5541 struct Lisp_Process *p = XPROCESS (proc);
5542 int rv;
5543 struct coding_system *coding;
5544 struct gcpro gcpro1;
5545 SIGTYPE (*volatile old_sigpipe) ();
5547 GCPRO1 (object);
5549 if (p->raw_status_new)
5550 update_status (p);
5551 if (! EQ (p->status, Qrun))
5552 error ("Process %s not running", SDATA (p->name));
5553 if (p->outfd < 0)
5554 error ("Output file descriptor of %s is closed", SDATA (p->name));
5556 coding = proc_encode_coding_system[p->outfd];
5557 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5559 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5560 || (BUFFERP (object)
5561 && !NILP (XBUFFER (object)->enable_multibyte_characters))
5562 || EQ (object, Qt))
5564 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5565 /* The coding system for encoding was changed to raw-text
5566 because we sent a unibyte text previously. Now we are
5567 sending a multibyte text, thus we must encode it by the
5568 original coding system specified for the current process. */
5569 setup_coding_system (p->encode_coding_system, coding);
5570 coding->src_multibyte = 1;
5572 else
5574 /* For sending a unibyte text, character code conversion should
5575 not take place but EOL conversion should. So, setup raw-text
5576 or one of the subsidiary if we have not yet done it. */
5577 if (CODING_REQUIRE_ENCODING (coding))
5579 if (CODING_REQUIRE_FLUSHING (coding))
5581 /* But, before changing the coding, we must flush out data. */
5582 coding->mode |= CODING_MODE_LAST_BLOCK;
5583 send_process (proc, "", 0, Qt);
5584 coding->mode &= CODING_MODE_LAST_BLOCK;
5586 setup_coding_system (raw_text_coding_system
5587 (Vlast_coding_system_used),
5588 coding);
5589 coding->src_multibyte = 0;
5592 coding->dst_multibyte = 0;
5594 if (CODING_REQUIRE_ENCODING (coding))
5596 coding->dst_object = Qt;
5597 if (BUFFERP (object))
5599 int from_byte, from, to;
5600 int save_pt, save_pt_byte;
5601 struct buffer *cur = current_buffer;
5603 set_buffer_internal (XBUFFER (object));
5604 save_pt = PT, save_pt_byte = PT_BYTE;
5606 from_byte = PTR_BYTE_POS (buf);
5607 from = BYTE_TO_CHAR (from_byte);
5608 to = BYTE_TO_CHAR (from_byte + len);
5609 TEMP_SET_PT_BOTH (from, from_byte);
5610 encode_coding_object (coding, object, from, from_byte,
5611 to, from_byte + len, Qt);
5612 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5613 set_buffer_internal (cur);
5615 else if (STRINGP (object))
5617 encode_coding_string (coding, object, 1);
5619 else
5621 coding->dst_object = make_unibyte_string (buf, len);
5622 coding->produced = len;
5625 len = coding->produced;
5626 buf = SDATA (coding->dst_object);
5629 if (pty_max_bytes == 0)
5631 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
5632 pty_max_bytes = fpathconf (p->outfd, _PC_MAX_CANON);
5633 if (pty_max_bytes < 0)
5634 pty_max_bytes = 250;
5635 #else
5636 pty_max_bytes = 250;
5637 #endif
5638 /* Deduct one, to leave space for the eof. */
5639 pty_max_bytes--;
5642 /* 2000-09-21: Emacs 20.7, sparc-sun-solaris-2.6, GCC 2.95.2,
5643 CFLAGS="-g -O": The value of the parameter `proc' is clobbered
5644 when returning with longjmp despite being declared volatile. */
5645 if (!setjmp (send_process_frame))
5647 process_sent_to = proc;
5648 while (len > 0)
5650 int this = len;
5652 /* Decide how much data we can send in one batch.
5653 Long lines need to be split into multiple batches. */
5654 if (p->pty_flag)
5656 /* Starting this at zero is always correct when not the first
5657 iteration because the previous iteration ended by sending C-d.
5658 It may not be correct for the first iteration
5659 if a partial line was sent in a separate send_process call.
5660 If that proves worth handling, we need to save linepos
5661 in the process object. */
5662 int linepos = 0;
5663 unsigned char *ptr = (unsigned char *) buf;
5664 unsigned char *end = (unsigned char *) buf + len;
5666 /* Scan through this text for a line that is too long. */
5667 while (ptr != end && linepos < pty_max_bytes)
5669 if (*ptr == '\n')
5670 linepos = 0;
5671 else
5672 linepos++;
5673 ptr++;
5675 /* If we found one, break the line there
5676 and put in a C-d to force the buffer through. */
5677 this = ptr - buf;
5680 /* Send this batch, using one or more write calls. */
5681 while (this > 0)
5683 int outfd = p->outfd;
5684 old_sigpipe = (SIGTYPE (*) ()) signal (SIGPIPE, send_process_trap);
5685 #ifdef DATAGRAM_SOCKETS
5686 if (DATAGRAM_CHAN_P (outfd))
5688 rv = sendto (outfd, (char *) buf, this,
5689 0, datagram_address[outfd].sa,
5690 datagram_address[outfd].len);
5691 if (rv < 0 && errno == EMSGSIZE)
5693 signal (SIGPIPE, old_sigpipe);
5694 report_file_error ("sending datagram",
5695 Fcons (proc, Qnil));
5698 else
5699 #endif
5701 rv = emacs_write (outfd, (char *) buf, this);
5702 #ifdef ADAPTIVE_READ_BUFFERING
5703 if (p->read_output_delay > 0
5704 && p->adaptive_read_buffering == 1)
5706 p->read_output_delay = 0;
5707 process_output_delay_count--;
5708 p->read_output_skip = 0;
5710 #endif
5712 signal (SIGPIPE, old_sigpipe);
5714 if (rv < 0)
5716 if (0
5717 #ifdef EWOULDBLOCK
5718 || errno == EWOULDBLOCK
5719 #endif
5720 #ifdef EAGAIN
5721 || errno == EAGAIN
5722 #endif
5724 /* Buffer is full. Wait, accepting input;
5725 that may allow the program
5726 to finish doing output and read more. */
5728 int offset = 0;
5730 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5731 /* A gross hack to work around a bug in FreeBSD.
5732 In the following sequence, read(2) returns
5733 bogus data:
5735 write(2) 1022 bytes
5736 write(2) 954 bytes, get EAGAIN
5737 read(2) 1024 bytes in process_read_output
5738 read(2) 11 bytes in process_read_output
5740 That is, read(2) returns more bytes than have
5741 ever been written successfully. The 1033 bytes
5742 read are the 1022 bytes written successfully
5743 after processing (for example with CRs added if
5744 the terminal is set up that way which it is
5745 here). The same bytes will be seen again in a
5746 later read(2), without the CRs. */
5748 if (errno == EAGAIN)
5750 int flags = FWRITE;
5751 ioctl (p->outfd, TIOCFLUSH, &flags);
5753 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5755 /* Running filters might relocate buffers or strings.
5756 Arrange to relocate BUF. */
5757 if (CODING_REQUIRE_ENCODING (coding))
5758 offset = buf - SDATA (coding->dst_object);
5759 else if (BUFFERP (object))
5760 offset = BUF_PTR_BYTE_POS (XBUFFER (object), buf);
5761 else if (STRINGP (object))
5762 offset = buf - SDATA (object);
5764 #ifdef EMACS_HAS_USECS
5765 wait_reading_process_output (0, 20000, 0, 0, Qnil, NULL, 0);
5766 #else
5767 wait_reading_process_output (1, 0, 0, 0, Qnil, NULL, 0);
5768 #endif
5770 if (CODING_REQUIRE_ENCODING (coding))
5771 buf = offset + SDATA (coding->dst_object);
5772 else if (BUFFERP (object))
5773 buf = BUF_BYTE_ADDRESS (XBUFFER (object), offset);
5774 else if (STRINGP (object))
5775 buf = offset + SDATA (object);
5777 rv = 0;
5779 else
5780 /* This is a real error. */
5781 report_file_error ("writing to process", Fcons (proc, Qnil));
5783 buf += rv;
5784 len -= rv;
5785 this -= rv;
5788 /* If we sent just part of the string, put in an EOF (C-d)
5789 to force it through, before we send the rest. */
5790 if (len > 0)
5791 Fprocess_send_eof (proc);
5794 else
5796 signal (SIGPIPE, old_sigpipe);
5797 proc = process_sent_to;
5798 p = XPROCESS (proc);
5799 p->raw_status_new = 0;
5800 p->status = Fcons (Qexit, Fcons (make_number (256), Qnil));
5801 p->tick = ++process_tick;
5802 deactivate_process (proc);
5803 error ("SIGPIPE raised on process %s; closed it", SDATA (p->name));
5806 UNGCPRO;
5809 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5810 3, 3, 0,
5811 doc: /* Send current contents of region as input to PROCESS.
5812 PROCESS may be a process, a buffer, the name of a process or buffer, or
5813 nil, indicating the current buffer's process.
5814 Called from program, takes three arguments, PROCESS, START and END.
5815 If the region is more than 500 characters long,
5816 it is sent in several bunches. This may happen even for shorter regions.
5817 Output from processes can arrive in between bunches. */)
5818 (process, start, end)
5819 Lisp_Object process, start, end;
5821 Lisp_Object proc;
5822 int start1, end1;
5824 proc = get_process (process);
5825 validate_region (&start, &end);
5827 if (XINT (start) < GPT && XINT (end) > GPT)
5828 move_gap (XINT (start));
5830 start1 = CHAR_TO_BYTE (XINT (start));
5831 end1 = CHAR_TO_BYTE (XINT (end));
5832 send_process (proc, BYTE_POS_ADDR (start1), end1 - start1,
5833 Fcurrent_buffer ());
5835 return Qnil;
5838 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5839 2, 2, 0,
5840 doc: /* Send PROCESS the contents of STRING as input.
5841 PROCESS may be a process, a buffer, the name of a process or buffer, or
5842 nil, indicating the current buffer's process.
5843 If STRING is more than 500 characters long,
5844 it is sent in several bunches. This may happen even for shorter strings.
5845 Output from processes can arrive in between bunches. */)
5846 (process, string)
5847 Lisp_Object process, string;
5849 Lisp_Object proc;
5850 CHECK_STRING (string);
5851 proc = get_process (process);
5852 send_process (proc, SDATA (string),
5853 SBYTES (string), string);
5854 return Qnil;
5857 /* Return the foreground process group for the tty/pty that
5858 the process P uses. */
5859 static int
5860 emacs_get_tty_pgrp (p)
5861 struct Lisp_Process *p;
5863 int gid = -1;
5865 #ifdef TIOCGPGRP
5866 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5868 int fd;
5869 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5870 master side. Try the slave side. */
5871 fd = emacs_open (SDATA (p->tty_name), O_RDONLY, 0);
5873 if (fd != -1)
5875 ioctl (fd, TIOCGPGRP, &gid);
5876 emacs_close (fd);
5879 #endif /* defined (TIOCGPGRP ) */
5881 return gid;
5884 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5885 Sprocess_running_child_p, 0, 1, 0,
5886 doc: /* Return t if PROCESS has given the terminal to a child.
5887 If the operating system does not make it possible to find out,
5888 return t unconditionally. */)
5889 (process)
5890 Lisp_Object process;
5892 /* Initialize in case ioctl doesn't exist or gives an error,
5893 in a way that will cause returning t. */
5894 int gid;
5895 Lisp_Object proc;
5896 struct Lisp_Process *p;
5898 proc = get_process (process);
5899 p = XPROCESS (proc);
5901 if (!EQ (p->type, Qreal))
5902 error ("Process %s is not a subprocess",
5903 SDATA (p->name));
5904 if (p->infd < 0)
5905 error ("Process %s is not active",
5906 SDATA (p->name));
5908 gid = emacs_get_tty_pgrp (p);
5910 if (gid == p->pid)
5911 return Qnil;
5912 return Qt;
5915 /* send a signal number SIGNO to PROCESS.
5916 If CURRENT_GROUP is t, that means send to the process group
5917 that currently owns the terminal being used to communicate with PROCESS.
5918 This is used for various commands in shell mode.
5919 If CURRENT_GROUP is lambda, that means send to the process group
5920 that currently owns the terminal, but only if it is NOT the shell itself.
5922 If NOMSG is zero, insert signal-announcements into process's buffers
5923 right away.
5925 If we can, we try to signal PROCESS by sending control characters
5926 down the pty. This allows us to signal inferiors who have changed
5927 their uid, for which killpg would return an EPERM error. */
5929 static void
5930 process_send_signal (process, signo, current_group, nomsg)
5931 Lisp_Object process;
5932 int signo;
5933 Lisp_Object current_group;
5934 int nomsg;
5936 Lisp_Object proc;
5937 register struct Lisp_Process *p;
5938 int gid;
5939 int no_pgrp = 0;
5941 proc = get_process (process);
5942 p = XPROCESS (proc);
5944 if (!EQ (p->type, Qreal))
5945 error ("Process %s is not a subprocess",
5946 SDATA (p->name));
5947 if (p->infd < 0)
5948 error ("Process %s is not active",
5949 SDATA (p->name));
5951 if (!p->pty_flag)
5952 current_group = Qnil;
5954 /* If we are using pgrps, get a pgrp number and make it negative. */
5955 if (NILP (current_group))
5956 /* Send the signal to the shell's process group. */
5957 gid = p->pid;
5958 else
5960 #ifdef SIGNALS_VIA_CHARACTERS
5961 /* If possible, send signals to the entire pgrp
5962 by sending an input character to it. */
5964 /* TERMIOS is the latest and bestest, and seems most likely to
5965 work. If the system has it, use it. */
5966 #ifdef HAVE_TERMIOS
5967 struct termios t;
5968 cc_t *sig_char = NULL;
5970 tcgetattr (p->infd, &t);
5972 switch (signo)
5974 case SIGINT:
5975 sig_char = &t.c_cc[VINTR];
5976 break;
5978 case SIGQUIT:
5979 sig_char = &t.c_cc[VQUIT];
5980 break;
5982 case SIGTSTP:
5983 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5984 sig_char = &t.c_cc[VSWTCH];
5985 #else
5986 sig_char = &t.c_cc[VSUSP];
5987 #endif
5988 break;
5991 if (sig_char && *sig_char != CDISABLE)
5993 send_process (proc, sig_char, 1, Qnil);
5994 return;
5996 /* If we can't send the signal with a character,
5997 fall through and send it another way. */
5998 #else /* ! HAVE_TERMIOS */
6000 /* On Berkeley descendants, the following IOCTL's retrieve the
6001 current control characters. */
6002 #if defined (TIOCGLTC) && defined (TIOCGETC)
6004 struct tchars c;
6005 struct ltchars lc;
6007 switch (signo)
6009 case SIGINT:
6010 ioctl (p->infd, TIOCGETC, &c);
6011 send_process (proc, &c.t_intrc, 1, Qnil);
6012 return;
6013 case SIGQUIT:
6014 ioctl (p->infd, TIOCGETC, &c);
6015 send_process (proc, &c.t_quitc, 1, Qnil);
6016 return;
6017 #ifdef SIGTSTP
6018 case SIGTSTP:
6019 ioctl (p->infd, TIOCGLTC, &lc);
6020 send_process (proc, &lc.t_suspc, 1, Qnil);
6021 return;
6022 #endif /* ! defined (SIGTSTP) */
6025 #else /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
6027 /* On SYSV descendants, the TCGETA ioctl retrieves the current control
6028 characters. */
6029 #ifdef TCGETA
6030 struct termio t;
6031 switch (signo)
6033 case SIGINT:
6034 ioctl (p->infd, TCGETA, &t);
6035 send_process (proc, &t.c_cc[VINTR], 1, Qnil);
6036 return;
6037 case SIGQUIT:
6038 ioctl (p->infd, TCGETA, &t);
6039 send_process (proc, &t.c_cc[VQUIT], 1, Qnil);
6040 return;
6041 #ifdef SIGTSTP
6042 case SIGTSTP:
6043 ioctl (p->infd, TCGETA, &t);
6044 send_process (proc, &t.c_cc[VSWTCH], 1, Qnil);
6045 return;
6046 #endif /* ! defined (SIGTSTP) */
6048 #else /* ! defined (TCGETA) */
6049 Your configuration files are messed up.
6050 /* If your system configuration files define SIGNALS_VIA_CHARACTERS,
6051 you'd better be using one of the alternatives above! */
6052 #endif /* ! defined (TCGETA) */
6053 #endif /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
6054 /* In this case, the code above should alway return. */
6055 abort ();
6056 #endif /* ! defined HAVE_TERMIOS */
6058 /* The code above may fall through if it can't
6059 handle the signal. */
6060 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6062 #ifdef TIOCGPGRP
6063 /* Get the current pgrp using the tty itself, if we have that.
6064 Otherwise, use the pty to get the pgrp.
6065 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6066 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6067 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6068 His patch indicates that if TIOCGPGRP returns an error, then
6069 we should just assume that p->pid is also the process group id. */
6071 gid = emacs_get_tty_pgrp (p);
6073 if (gid == -1)
6074 /* If we can't get the information, assume
6075 the shell owns the tty. */
6076 gid = p->pid;
6078 /* It is not clear whether anything really can set GID to -1.
6079 Perhaps on some system one of those ioctls can or could do so.
6080 Or perhaps this is vestigial. */
6081 if (gid == -1)
6082 no_pgrp = 1;
6083 #else /* ! defined (TIOCGPGRP ) */
6084 /* Can't select pgrps on this system, so we know that
6085 the child itself heads the pgrp. */
6086 gid = p->pid;
6087 #endif /* ! defined (TIOCGPGRP ) */
6089 /* If current_group is lambda, and the shell owns the terminal,
6090 don't send any signal. */
6091 if (EQ (current_group, Qlambda) && gid == p->pid)
6092 return;
6095 switch (signo)
6097 #ifdef SIGCONT
6098 case SIGCONT:
6099 p->raw_status_new = 0;
6100 p->status = Qrun;
6101 p->tick = ++process_tick;
6102 if (!nomsg)
6103 status_notify (NULL);
6104 break;
6105 #endif /* ! defined (SIGCONT) */
6106 case SIGINT:
6107 case SIGQUIT:
6108 case SIGKILL:
6109 flush_pending_output (p->infd);
6110 break;
6113 /* If we don't have process groups, send the signal to the immediate
6114 subprocess. That isn't really right, but it's better than any
6115 obvious alternative. */
6116 if (no_pgrp)
6118 kill (p->pid, signo);
6119 return;
6122 /* gid may be a pid, or minus a pgrp's number */
6123 #ifdef TIOCSIGSEND
6124 if (!NILP (current_group))
6126 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
6127 EMACS_KILLPG (gid, signo);
6129 else
6131 gid = - p->pid;
6132 kill (gid, signo);
6134 #else /* ! defined (TIOCSIGSEND) */
6135 EMACS_KILLPG (gid, signo);
6136 #endif /* ! defined (TIOCSIGSEND) */
6139 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6140 doc: /* Interrupt process PROCESS.
6141 PROCESS may be a process, a buffer, or the name of a process or buffer.
6142 No arg or nil means current buffer's process.
6143 Second arg CURRENT-GROUP non-nil means send signal to
6144 the current process-group of the process's controlling terminal
6145 rather than to the process's own process group.
6146 If the process is a shell, this means interrupt current subjob
6147 rather than the shell.
6149 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6150 don't send the signal. */)
6151 (process, current_group)
6152 Lisp_Object process, current_group;
6154 process_send_signal (process, SIGINT, current_group, 0);
6155 return process;
6158 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6159 doc: /* Kill process PROCESS. May be process or name of one.
6160 See function `interrupt-process' for more details on usage. */)
6161 (process, current_group)
6162 Lisp_Object process, current_group;
6164 process_send_signal (process, SIGKILL, current_group, 0);
6165 return process;
6168 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6169 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6170 See function `interrupt-process' for more details on usage. */)
6171 (process, current_group)
6172 Lisp_Object process, current_group;
6174 process_send_signal (process, SIGQUIT, current_group, 0);
6175 return process;
6178 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6179 doc: /* Stop process PROCESS. May be process or name of one.
6180 See function `interrupt-process' for more details on usage.
6181 If PROCESS is a network or serial process, inhibit handling of incoming
6182 traffic. */)
6183 (process, current_group)
6184 Lisp_Object process, current_group;
6186 #ifdef HAVE_SOCKETS
6187 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6189 struct Lisp_Process *p;
6191 p = XPROCESS (process);
6192 if (NILP (p->command)
6193 && p->infd >= 0)
6195 FD_CLR (p->infd, &input_wait_mask);
6196 FD_CLR (p->infd, &non_keyboard_wait_mask);
6198 p->command = Qt;
6199 return process;
6201 #endif
6202 #ifndef SIGTSTP
6203 error ("No SIGTSTP support");
6204 #else
6205 process_send_signal (process, SIGTSTP, current_group, 0);
6206 #endif
6207 return process;
6210 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6211 doc: /* Continue process PROCESS. May be process or name of one.
6212 See function `interrupt-process' for more details on usage.
6213 If PROCESS is a network or serial process, resume handling of incoming
6214 traffic. */)
6215 (process, current_group)
6216 Lisp_Object process, current_group;
6218 #ifdef HAVE_SOCKETS
6219 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6221 struct Lisp_Process *p;
6223 p = XPROCESS (process);
6224 if (EQ (p->command, Qt)
6225 && p->infd >= 0
6226 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6228 FD_SET (p->infd, &input_wait_mask);
6229 FD_SET (p->infd, &non_keyboard_wait_mask);
6230 #ifdef WINDOWSNT
6231 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6232 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6233 #endif
6234 #ifdef HAVE_TERMIOS
6235 tcflush (p->infd, TCIFLUSH);
6236 #endif
6238 p->command = Qnil;
6239 return process;
6241 #endif
6242 #ifdef SIGCONT
6243 process_send_signal (process, SIGCONT, current_group, 0);
6244 #else
6245 error ("No SIGCONT support");
6246 #endif
6247 return process;
6250 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6251 2, 2, "sProcess (name or number): \nnSignal code: ",
6252 doc: /* Send PROCESS the signal with code SIGCODE.
6253 PROCESS may also be a number specifying the process id of the
6254 process to signal; in this case, the process need not be a child of
6255 this Emacs.
6256 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6257 (process, sigcode)
6258 Lisp_Object process, sigcode;
6260 pid_t pid;
6262 if (INTEGERP (process))
6264 pid = XINT (process);
6265 goto got_it;
6268 if (FLOATP (process))
6270 pid = (pid_t) XFLOAT_DATA (process);
6271 goto got_it;
6274 if (STRINGP (process))
6276 Lisp_Object tem;
6277 if (tem = Fget_process (process), NILP (tem))
6279 pid = XINT (Fstring_to_number (process, make_number (10)));
6280 if (pid > 0)
6281 goto got_it;
6283 process = tem;
6285 else
6286 process = get_process (process);
6288 if (NILP (process))
6289 return process;
6291 CHECK_PROCESS (process);
6292 pid = XPROCESS (process)->pid;
6293 if (pid <= 0)
6294 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6296 got_it:
6298 #define parse_signal(NAME, VALUE) \
6299 else if (!xstrcasecmp (name, NAME)) \
6300 XSETINT (sigcode, VALUE)
6302 if (INTEGERP (sigcode))
6304 else
6306 unsigned char *name;
6308 CHECK_SYMBOL (sigcode);
6309 name = SDATA (SYMBOL_NAME (sigcode));
6311 if (!strncmp(name, "SIG", 3) || !strncmp(name, "sig", 3))
6312 name += 3;
6314 if (0)
6316 #ifdef SIGUSR1
6317 parse_signal ("usr1", SIGUSR1);
6318 #endif
6319 #ifdef SIGUSR2
6320 parse_signal ("usr2", SIGUSR2);
6321 #endif
6322 #ifdef SIGTERM
6323 parse_signal ("term", SIGTERM);
6324 #endif
6325 #ifdef SIGHUP
6326 parse_signal ("hup", SIGHUP);
6327 #endif
6328 #ifdef SIGINT
6329 parse_signal ("int", SIGINT);
6330 #endif
6331 #ifdef SIGQUIT
6332 parse_signal ("quit", SIGQUIT);
6333 #endif
6334 #ifdef SIGILL
6335 parse_signal ("ill", SIGILL);
6336 #endif
6337 #ifdef SIGABRT
6338 parse_signal ("abrt", SIGABRT);
6339 #endif
6340 #ifdef SIGEMT
6341 parse_signal ("emt", SIGEMT);
6342 #endif
6343 #ifdef SIGKILL
6344 parse_signal ("kill", SIGKILL);
6345 #endif
6346 #ifdef SIGFPE
6347 parse_signal ("fpe", SIGFPE);
6348 #endif
6349 #ifdef SIGBUS
6350 parse_signal ("bus", SIGBUS);
6351 #endif
6352 #ifdef SIGSEGV
6353 parse_signal ("segv", SIGSEGV);
6354 #endif
6355 #ifdef SIGSYS
6356 parse_signal ("sys", SIGSYS);
6357 #endif
6358 #ifdef SIGPIPE
6359 parse_signal ("pipe", SIGPIPE);
6360 #endif
6361 #ifdef SIGALRM
6362 parse_signal ("alrm", SIGALRM);
6363 #endif
6364 #ifdef SIGURG
6365 parse_signal ("urg", SIGURG);
6366 #endif
6367 #ifdef SIGSTOP
6368 parse_signal ("stop", SIGSTOP);
6369 #endif
6370 #ifdef SIGTSTP
6371 parse_signal ("tstp", SIGTSTP);
6372 #endif
6373 #ifdef SIGCONT
6374 parse_signal ("cont", SIGCONT);
6375 #endif
6376 #ifdef SIGCHLD
6377 parse_signal ("chld", SIGCHLD);
6378 #endif
6379 #ifdef SIGTTIN
6380 parse_signal ("ttin", SIGTTIN);
6381 #endif
6382 #ifdef SIGTTOU
6383 parse_signal ("ttou", SIGTTOU);
6384 #endif
6385 #ifdef SIGIO
6386 parse_signal ("io", SIGIO);
6387 #endif
6388 #ifdef SIGXCPU
6389 parse_signal ("xcpu", SIGXCPU);
6390 #endif
6391 #ifdef SIGXFSZ
6392 parse_signal ("xfsz", SIGXFSZ);
6393 #endif
6394 #ifdef SIGVTALRM
6395 parse_signal ("vtalrm", SIGVTALRM);
6396 #endif
6397 #ifdef SIGPROF
6398 parse_signal ("prof", SIGPROF);
6399 #endif
6400 #ifdef SIGWINCH
6401 parse_signal ("winch", SIGWINCH);
6402 #endif
6403 #ifdef SIGINFO
6404 parse_signal ("info", SIGINFO);
6405 #endif
6406 else
6407 error ("Undefined signal name %s", name);
6410 #undef parse_signal
6412 return make_number (kill (pid, XINT (sigcode)));
6415 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6416 doc: /* Make PROCESS see end-of-file in its input.
6417 EOF comes after any text already sent to it.
6418 PROCESS may be a process, a buffer, the name of a process or buffer, or
6419 nil, indicating the current buffer's process.
6420 If PROCESS is a network connection, or is a process communicating
6421 through a pipe (as opposed to a pty), then you cannot send any more
6422 text to PROCESS after you call this function.
6423 If PROCESS is a serial process, wait until all output written to the
6424 process has been transmitted to the serial port. */)
6425 (process)
6426 Lisp_Object process;
6428 Lisp_Object proc;
6429 struct coding_system *coding;
6431 if (DATAGRAM_CONN_P (process))
6432 return process;
6434 proc = get_process (process);
6435 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
6437 /* Make sure the process is really alive. */
6438 if (XPROCESS (proc)->raw_status_new)
6439 update_status (XPROCESS (proc));
6440 if (! EQ (XPROCESS (proc)->status, Qrun))
6441 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6443 if (CODING_REQUIRE_FLUSHING (coding))
6445 coding->mode |= CODING_MODE_LAST_BLOCK;
6446 send_process (proc, "", 0, Qnil);
6449 if (XPROCESS (proc)->pty_flag)
6450 send_process (proc, "\004", 1, Qnil);
6451 else if (EQ (XPROCESS (proc)->type, Qserial))
6453 #ifdef HAVE_TERMIOS
6454 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6455 error ("tcdrain() failed: %s", emacs_strerror (errno));
6456 #endif
6457 /* Do nothing on Windows because writes are blocking. */
6459 else
6461 int old_outfd, new_outfd;
6463 #ifdef HAVE_SHUTDOWN
6464 /* If this is a network connection, or socketpair is used
6465 for communication with the subprocess, call shutdown to cause EOF.
6466 (In some old system, shutdown to socketpair doesn't work.
6467 Then we just can't win.) */
6468 if (EQ (XPROCESS (proc)->type, Qnetwork)
6469 || XPROCESS (proc)->outfd == XPROCESS (proc)->infd)
6470 shutdown (XPROCESS (proc)->outfd, 1);
6471 /* In case of socketpair, outfd == infd, so don't close it. */
6472 if (XPROCESS (proc)->outfd != XPROCESS (proc)->infd)
6473 emacs_close (XPROCESS (proc)->outfd);
6474 #else /* not HAVE_SHUTDOWN */
6475 emacs_close (XPROCESS (proc)->outfd);
6476 #endif /* not HAVE_SHUTDOWN */
6477 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6478 if (new_outfd < 0)
6479 abort ();
6480 old_outfd = XPROCESS (proc)->outfd;
6482 if (!proc_encode_coding_system[new_outfd])
6483 proc_encode_coding_system[new_outfd]
6484 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
6485 bcopy (proc_encode_coding_system[old_outfd],
6486 proc_encode_coding_system[new_outfd],
6487 sizeof (struct coding_system));
6488 bzero (proc_encode_coding_system[old_outfd],
6489 sizeof (struct coding_system));
6491 XPROCESS (proc)->outfd = new_outfd;
6493 return process;
6496 /* Kill all processes associated with `buffer'.
6497 If `buffer' is nil, kill all processes */
6499 void
6500 kill_buffer_processes (buffer)
6501 Lisp_Object buffer;
6503 Lisp_Object tail, proc;
6505 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6507 proc = XCDR (XCAR (tail));
6508 if (PROCESSP (proc)
6509 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
6511 if (NETCONN_P (proc) || SERIALCONN_P (proc))
6512 Fdelete_process (proc);
6513 else if (XPROCESS (proc)->infd >= 0)
6514 process_send_signal (proc, SIGHUP, Qnil, 1);
6519 /* On receipt of a signal that a child status has changed, loop asking
6520 about children with changed statuses until the system says there
6521 are no more.
6523 All we do is change the status; we do not run sentinels or print
6524 notifications. That is saved for the next time keyboard input is
6525 done, in order to avoid timing errors.
6527 ** WARNING: this can be called during garbage collection.
6528 Therefore, it must not be fooled by the presence of mark bits in
6529 Lisp objects.
6531 ** USG WARNING: Although it is not obvious from the documentation
6532 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6533 signal() before executing at least one wait(), otherwise the
6534 handler will be called again, resulting in an infinite loop. The
6535 relevant portion of the documentation reads "SIGCLD signals will be
6536 queued and the signal-catching function will be continually
6537 reentered until the queue is empty". Invoking signal() causes the
6538 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6539 Inc.
6541 ** Malloc WARNING: This should never call malloc either directly or
6542 indirectly; if it does, that is a bug */
6544 #ifdef SIGCHLD
6545 SIGTYPE
6546 sigchld_handler (signo)
6547 int signo;
6549 int old_errno = errno;
6550 Lisp_Object proc;
6551 register struct Lisp_Process *p;
6552 extern EMACS_TIME *input_available_clear_time;
6554 SIGNAL_THREAD_CHECK (signo);
6556 while (1)
6558 pid_t pid;
6559 int w;
6560 Lisp_Object tail;
6562 #ifdef WNOHANG
6563 #ifndef WUNTRACED
6564 #define WUNTRACED 0
6565 #endif /* no WUNTRACED */
6566 /* Keep trying to get a status until we get a definitive result. */
6569 errno = 0;
6570 pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
6572 while (pid < 0 && errno == EINTR);
6574 if (pid <= 0)
6576 /* PID == 0 means no processes found, PID == -1 means a real
6577 failure. We have done all our job, so return. */
6579 /* USG systems forget handlers when they are used;
6580 must reestablish each time */
6581 #if defined (USG) && !defined (POSIX_SIGNALS)
6582 signal (signo, sigchld_handler); /* WARNING - must come after wait3() */
6583 #endif
6584 errno = old_errno;
6585 return;
6587 #else
6588 pid = wait (&w);
6589 #endif /* no WNOHANG */
6591 /* Find the process that signaled us, and record its status. */
6593 /* The process can have been deleted by Fdelete_process. */
6594 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6596 Lisp_Object xpid = XCAR (tail);
6597 if ((INTEGERP (xpid) && pid == (pid_t) XINT (xpid))
6598 || (FLOATP (xpid) && pid == (pid_t) XFLOAT_DATA (xpid)))
6600 XSETCAR (tail, Qnil);
6601 goto sigchld_end_of_loop;
6605 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6606 p = 0;
6607 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6609 proc = XCDR (XCAR (tail));
6610 p = XPROCESS (proc);
6611 if (EQ (p->type, Qreal) && p->pid == pid)
6612 break;
6613 p = 0;
6616 /* Look for an asynchronous process whose pid hasn't been filled
6617 in yet. */
6618 if (p == 0)
6619 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6621 proc = XCDR (XCAR (tail));
6622 p = XPROCESS (proc);
6623 if (p->pid == -1)
6624 break;
6625 p = 0;
6628 /* Change the status of the process that was found. */
6629 if (p != 0)
6631 int clear_desc_flag = 0;
6633 p->tick = ++process_tick;
6634 p->raw_status = w;
6635 p->raw_status_new = 1;
6637 /* If process has terminated, stop waiting for its output. */
6638 if ((WIFSIGNALED (w) || WIFEXITED (w))
6639 && p->infd >= 0)
6640 clear_desc_flag = 1;
6642 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
6643 if (clear_desc_flag)
6645 FD_CLR (p->infd, &input_wait_mask);
6646 FD_CLR (p->infd, &non_keyboard_wait_mask);
6649 /* Tell wait_reading_process_output that it needs to wake up and
6650 look around. */
6651 if (input_available_clear_time)
6652 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6655 /* There was no asynchronous process found for that pid: we have
6656 a synchronous process. */
6657 else
6659 synch_process_alive = 0;
6661 /* Report the status of the synchronous process. */
6662 if (WIFEXITED (w))
6663 synch_process_retcode = WRETCODE (w);
6664 else if (WIFSIGNALED (w))
6665 synch_process_termsig = WTERMSIG (w);
6667 /* Tell wait_reading_process_output that it needs to wake up and
6668 look around. */
6669 if (input_available_clear_time)
6670 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6673 sigchld_end_of_loop:
6676 /* On some systems, we must return right away.
6677 If any more processes want to signal us, we will
6678 get another signal.
6679 Otherwise (on systems that have WNOHANG), loop around
6680 to use up all the processes that have something to tell us. */
6681 #if (defined WINDOWSNT \
6682 || (defined USG && !defined GNU_LINUX \
6683 && !(defined HPUX && defined WNOHANG)))
6684 #if defined (USG) && ! defined (POSIX_SIGNALS)
6685 signal (signo, sigchld_handler);
6686 #endif
6687 errno = old_errno;
6688 return;
6689 #endif /* USG, but not HPUX with WNOHANG */
6692 #endif /* SIGCHLD */
6695 static Lisp_Object
6696 exec_sentinel_unwind (data)
6697 Lisp_Object data;
6699 XPROCESS (XCAR (data))->sentinel = XCDR (data);
6700 return Qnil;
6703 static Lisp_Object
6704 exec_sentinel_error_handler (error)
6705 Lisp_Object error;
6707 cmd_error_internal (error, "error in process sentinel: ");
6708 Vinhibit_quit = Qt;
6709 update_echo_area ();
6710 Fsleep_for (make_number (2), Qnil);
6711 return Qt;
6714 static void
6715 exec_sentinel (proc, reason)
6716 Lisp_Object proc, reason;
6718 Lisp_Object sentinel, obuffer, odeactivate, okeymap;
6719 register struct Lisp_Process *p = XPROCESS (proc);
6720 int count = SPECPDL_INDEX ();
6721 int outer_running_asynch_code = running_asynch_code;
6722 int waiting = waiting_for_user_input_p;
6724 if (inhibit_sentinels)
6725 return;
6727 /* No need to gcpro these, because all we do with them later
6728 is test them for EQness, and none of them should be a string. */
6729 odeactivate = Vdeactivate_mark;
6730 XSETBUFFER (obuffer, current_buffer);
6731 okeymap = current_buffer->keymap;
6733 sentinel = p->sentinel;
6734 if (NILP (sentinel))
6735 return;
6737 /* Zilch the sentinel while it's running, to avoid recursive invocations;
6738 assure that it gets restored no matter how the sentinel exits. */
6739 p->sentinel = Qnil;
6740 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
6741 /* Inhibit quit so that random quits don't screw up a running filter. */
6742 specbind (Qinhibit_quit, Qt);
6743 specbind (Qlast_nonmenu_event, Qt);
6745 /* In case we get recursively called,
6746 and we already saved the match data nonrecursively,
6747 save the same match data in safely recursive fashion. */
6748 if (outer_running_asynch_code)
6750 Lisp_Object tem;
6751 tem = Fmatch_data (Qnil, Qnil, Qnil);
6752 restore_search_regs ();
6753 record_unwind_save_match_data ();
6754 Fset_match_data (tem, Qt);
6757 /* For speed, if a search happens within this code,
6758 save the match data in a special nonrecursive fashion. */
6759 running_asynch_code = 1;
6761 internal_condition_case_1 (read_process_output_call,
6762 Fcons (sentinel,
6763 Fcons (proc, Fcons (reason, Qnil))),
6764 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6765 exec_sentinel_error_handler);
6767 /* If we saved the match data nonrecursively, restore it now. */
6768 restore_search_regs ();
6769 running_asynch_code = outer_running_asynch_code;
6771 Vdeactivate_mark = odeactivate;
6773 /* Restore waiting_for_user_input_p as it was
6774 when we were called, in case the filter clobbered it. */
6775 waiting_for_user_input_p = waiting;
6777 #if 0
6778 if (! EQ (Fcurrent_buffer (), obuffer)
6779 || ! EQ (current_buffer->keymap, okeymap))
6780 #endif
6781 /* But do it only if the caller is actually going to read events.
6782 Otherwise there's no need to make him wake up, and it could
6783 cause trouble (for example it would make sit_for return). */
6784 if (waiting_for_user_input_p == -1)
6785 record_asynch_buffer_change ();
6787 unbind_to (count, Qnil);
6790 /* Report all recent events of a change in process status
6791 (either run the sentinel or output a message).
6792 This is usually done while Emacs is waiting for keyboard input
6793 but can be done at other times. */
6795 static void
6796 status_notify (deleting_process)
6797 struct Lisp_Process *deleting_process;
6799 register Lisp_Object proc, buffer;
6800 Lisp_Object tail, msg;
6801 struct gcpro gcpro1, gcpro2;
6803 tail = Qnil;
6804 msg = Qnil;
6805 /* We need to gcpro tail; if read_process_output calls a filter
6806 which deletes a process and removes the cons to which tail points
6807 from Vprocess_alist, and then causes a GC, tail is an unprotected
6808 reference. */
6809 GCPRO2 (tail, msg);
6811 /* Set this now, so that if new processes are created by sentinels
6812 that we run, we get called again to handle their status changes. */
6813 update_tick = process_tick;
6815 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6817 Lisp_Object symbol;
6818 register struct Lisp_Process *p;
6820 proc = Fcdr (XCAR (tail));
6821 p = XPROCESS (proc);
6823 if (p->tick != p->update_tick)
6825 p->update_tick = p->tick;
6827 /* If process is still active, read any output that remains. */
6828 while (! EQ (p->filter, Qt)
6829 && ! EQ (p->status, Qconnect)
6830 && ! EQ (p->status, Qlisten)
6831 /* Network or serial process not stopped: */
6832 && ! EQ (p->command, Qt)
6833 && p->infd >= 0
6834 && p != deleting_process
6835 && read_process_output (proc, p->infd) > 0);
6837 buffer = p->buffer;
6839 /* Get the text to use for the message. */
6840 if (p->raw_status_new)
6841 update_status (p);
6842 msg = status_message (p);
6844 /* If process is terminated, deactivate it or delete it. */
6845 symbol = p->status;
6846 if (CONSP (p->status))
6847 symbol = XCAR (p->status);
6849 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6850 || EQ (symbol, Qclosed))
6852 if (delete_exited_processes)
6853 remove_process (proc);
6854 else
6855 deactivate_process (proc);
6858 /* The actions above may have further incremented p->tick.
6859 So set p->update_tick again
6860 so that an error in the sentinel will not cause
6861 this code to be run again. */
6862 p->update_tick = p->tick;
6863 /* Now output the message suitably. */
6864 if (!NILP (p->sentinel))
6865 exec_sentinel (proc, msg);
6866 /* Don't bother with a message in the buffer
6867 when a process becomes runnable. */
6868 else if (!EQ (symbol, Qrun) && !NILP (buffer))
6870 Lisp_Object ro, tem;
6871 struct buffer *old = current_buffer;
6872 int opoint, opoint_byte;
6873 int before, before_byte;
6875 ro = XBUFFER (buffer)->read_only;
6877 /* Avoid error if buffer is deleted
6878 (probably that's why the process is dead, too) */
6879 if (NILP (XBUFFER (buffer)->name))
6880 continue;
6881 Fset_buffer (buffer);
6883 opoint = PT;
6884 opoint_byte = PT_BYTE;
6885 /* Insert new output into buffer
6886 at the current end-of-output marker,
6887 thus preserving logical ordering of input and output. */
6888 if (XMARKER (p->mark)->buffer)
6889 Fgoto_char (p->mark);
6890 else
6891 SET_PT_BOTH (ZV, ZV_BYTE);
6893 before = PT;
6894 before_byte = PT_BYTE;
6896 tem = current_buffer->read_only;
6897 current_buffer->read_only = Qnil;
6898 insert_string ("\nProcess ");
6899 Finsert (1, &p->name);
6900 insert_string (" ");
6901 Finsert (1, &msg);
6902 current_buffer->read_only = tem;
6903 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6905 if (opoint >= before)
6906 SET_PT_BOTH (opoint + (PT - before),
6907 opoint_byte + (PT_BYTE - before_byte));
6908 else
6909 SET_PT_BOTH (opoint, opoint_byte);
6911 set_buffer_internal (old);
6914 } /* end for */
6916 update_mode_lines++; /* in case buffers use %s in mode-line-format */
6917 redisplay_preserve_echo_area (13);
6919 UNGCPRO;
6923 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6924 Sset_process_coding_system, 1, 3, 0,
6925 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6926 DECODING will be used to decode subprocess output and ENCODING to
6927 encode subprocess input. */)
6928 (process, decoding, encoding)
6929 register Lisp_Object process, decoding, encoding;
6931 register struct Lisp_Process *p;
6933 CHECK_PROCESS (process);
6934 p = XPROCESS (process);
6935 if (p->infd < 0)
6936 error ("Input file descriptor of %s closed", SDATA (p->name));
6937 if (p->outfd < 0)
6938 error ("Output file descriptor of %s closed", SDATA (p->name));
6939 Fcheck_coding_system (decoding);
6940 Fcheck_coding_system (encoding);
6941 encoding = coding_inherit_eol_type (encoding, Qnil);
6942 p->decode_coding_system = decoding;
6943 p->encode_coding_system = encoding;
6944 setup_process_coding_systems (process);
6946 return Qnil;
6949 DEFUN ("process-coding-system",
6950 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6951 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6952 (process)
6953 register Lisp_Object process;
6955 CHECK_PROCESS (process);
6956 return Fcons (XPROCESS (process)->decode_coding_system,
6957 XPROCESS (process)->encode_coding_system);
6960 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6961 Sset_process_filter_multibyte, 2, 2, 0,
6962 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6963 If FLAG is non-nil, the filter is given multibyte strings.
6964 If FLAG is nil, the filter is given unibyte strings. In this case,
6965 all character code conversion except for end-of-line conversion is
6966 suppressed. */)
6967 (process, flag)
6968 Lisp_Object process, flag;
6970 register struct Lisp_Process *p;
6972 CHECK_PROCESS (process);
6973 p = XPROCESS (process);
6974 if (NILP (flag))
6975 p->decode_coding_system = raw_text_coding_system (p->decode_coding_system);
6976 setup_process_coding_systems (process);
6978 return Qnil;
6981 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6982 Sprocess_filter_multibyte_p, 1, 1, 0,
6983 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6984 (process)
6985 Lisp_Object process;
6987 register struct Lisp_Process *p;
6988 struct coding_system *coding;
6990 CHECK_PROCESS (process);
6991 p = XPROCESS (process);
6992 coding = proc_decode_coding_system[p->infd];
6993 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6998 /* Add DESC to the set of keyboard input descriptors. */
7000 void
7001 add_keyboard_wait_descriptor (desc)
7002 int desc;
7004 FD_SET (desc, &input_wait_mask);
7005 FD_SET (desc, &non_process_wait_mask);
7006 if (desc > max_keyboard_desc)
7007 max_keyboard_desc = desc;
7010 static int add_gpm_wait_descriptor_called_flag;
7012 void
7013 add_gpm_wait_descriptor (desc)
7014 int desc;
7016 if (! add_gpm_wait_descriptor_called_flag)
7017 FD_CLR (0, &input_wait_mask);
7018 add_gpm_wait_descriptor_called_flag = 1;
7019 FD_SET (desc, &input_wait_mask);
7020 FD_SET (desc, &gpm_wait_mask);
7021 if (desc > max_gpm_desc)
7022 max_gpm_desc = desc;
7025 /* From now on, do not expect DESC to give keyboard input. */
7027 void
7028 delete_keyboard_wait_descriptor (desc)
7029 int desc;
7031 int fd;
7032 int lim = max_keyboard_desc;
7034 FD_CLR (desc, &input_wait_mask);
7035 FD_CLR (desc, &non_process_wait_mask);
7037 if (desc == max_keyboard_desc)
7038 for (fd = 0; fd < lim; fd++)
7039 if (FD_ISSET (fd, &input_wait_mask)
7040 && !FD_ISSET (fd, &non_keyboard_wait_mask)
7041 && !FD_ISSET (fd, &gpm_wait_mask))
7042 max_keyboard_desc = fd;
7045 void
7046 delete_gpm_wait_descriptor (desc)
7047 int desc;
7049 int fd;
7050 int lim = max_gpm_desc;
7052 FD_CLR (desc, &input_wait_mask);
7053 FD_CLR (desc, &non_process_wait_mask);
7055 if (desc == max_gpm_desc)
7056 for (fd = 0; fd < lim; fd++)
7057 if (FD_ISSET (fd, &input_wait_mask)
7058 && !FD_ISSET (fd, &non_keyboard_wait_mask)
7059 && !FD_ISSET (fd, &non_process_wait_mask))
7060 max_gpm_desc = fd;
7063 /* Return nonzero if *MASK has a bit set
7064 that corresponds to one of the keyboard input descriptors. */
7066 static int
7067 keyboard_bit_set (mask)
7068 SELECT_TYPE *mask;
7070 int fd;
7072 for (fd = 0; fd <= max_keyboard_desc; fd++)
7073 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
7074 && !FD_ISSET (fd, &non_keyboard_wait_mask))
7075 return 1;
7077 return 0;
7080 /* Enumeration of and access to system processes a-la ps(1). */
7082 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7083 0, 0, 0,
7084 doc: /* Return a list of numerical process IDs of all running processes.
7085 If this functionality is unsupported, return nil.
7087 See `process-attributes' for getting attributes of a process given its ID. */)
7090 return list_system_processes ();
7093 DEFUN ("process-attributes", Fprocess_attributes,
7094 Sprocess_attributes, 1, 1, 0,
7095 doc: /* Return attributes of the process given by its PID, a number.
7097 Value is an alist where each element is a cons cell of the form
7099 \(KEY . VALUE)
7101 If this functionality is unsupported, the value is nil.
7103 See `list-system-processes' for getting a list of all process IDs.
7105 The KEYs of the attributes that this function may return are listed
7106 below, together with the type of the associated VALUE (in parentheses).
7107 Not all platforms support all of these attributes; unsupported
7108 attributes will not appear in the returned alist.
7109 Unless explicitly indicated otherwise, numbers can have either
7110 integer or floating point values.
7112 euid -- Effective user User ID of the process (number)
7113 user -- User name corresponding to euid (string)
7114 egid -- Effective user Group ID of the process (number)
7115 group -- Group name corresponding to egid (string)
7116 comm -- Command name (executable name only) (string)
7117 state -- Process state code, such as "S", "R", or "T" (string)
7118 ppid -- Parent process ID (number)
7119 pgrp -- Process group ID (number)
7120 sess -- Session ID, i.e. process ID of session leader (number)
7121 ttname -- Controlling tty name (string)
7122 tpgid -- ID of foreground process group on the process's tty (number)
7123 minflt -- number of minor page faults (number)
7124 majflt -- number of major page faults (number)
7125 cminflt -- cumulative number of minor page faults (number)
7126 cmajflt -- cumulative number of major page faults (number)
7127 utime -- user time used by the process, in the (HIGH LOW USEC) format
7128 stime -- system time used by the process, in the (HIGH LOW USEC) format
7129 time -- sum of utime and stime, in the (HIGH LOW USEC) format
7130 cutime -- user time used by the process and its children, (HIGH LOW USEC)
7131 cstime -- system time used by the process and its children, (HIGH LOW USEC)
7132 ctime -- sum of cutime and cstime, in the (HIGH LOW USEC) format
7133 pri -- priority of the process (number)
7134 nice -- nice value of the process (number)
7135 thcount -- process thread count (number)
7136 start -- time the process started, in the (HIGH LOW USEC) format
7137 vsize -- virtual memory size of the process in KB's (number)
7138 rss -- resident set size of the process in KB's (number)
7139 etime -- elapsed time the process is running, in (HIGH LOW USEC) format
7140 pcpu -- percents of CPU time used by the process (floating-point number)
7141 pmem -- percents of total physical memory used by process's resident set
7142 (floating-point number)
7143 args -- command line which invoked the process (string). */)
7144 (pid)
7146 Lisp_Object pid;
7148 return system_process_attributes (pid);
7151 void
7152 init_process ()
7154 register int i;
7156 inhibit_sentinels = 0;
7158 #ifdef SIGCHLD
7159 #ifndef CANNOT_DUMP
7160 if (! noninteractive || initialized)
7161 #endif
7162 signal (SIGCHLD, sigchld_handler);
7163 #endif
7165 FD_ZERO (&input_wait_mask);
7166 FD_ZERO (&non_keyboard_wait_mask);
7167 FD_ZERO (&non_process_wait_mask);
7168 max_process_desc = 0;
7170 #ifdef NON_BLOCKING_CONNECT
7171 FD_ZERO (&connect_wait_mask);
7172 num_pending_connects = 0;
7173 #endif
7175 #ifdef ADAPTIVE_READ_BUFFERING
7176 process_output_delay_count = 0;
7177 process_output_skip = 0;
7178 #endif
7180 /* Don't do this, it caused infinite select loops. The display
7181 method should call add_keyboard_wait_descriptor on stdin if it
7182 needs that. */
7183 #if 0
7184 FD_SET (0, &input_wait_mask);
7185 #endif
7187 Vprocess_alist = Qnil;
7188 #ifdef SIGCHLD
7189 deleted_pid_list = Qnil;
7190 #endif
7191 for (i = 0; i < MAXDESC; i++)
7193 chan_process[i] = Qnil;
7194 proc_buffered_char[i] = -1;
7196 bzero (proc_decode_coding_system, sizeof proc_decode_coding_system);
7197 bzero (proc_encode_coding_system, sizeof proc_encode_coding_system);
7198 #ifdef DATAGRAM_SOCKETS
7199 bzero (datagram_address, sizeof datagram_address);
7200 #endif
7202 #ifdef HAVE_SOCKETS
7204 Lisp_Object subfeatures = Qnil;
7205 struct socket_options *sopt;
7207 #define ADD_SUBFEATURE(key, val) \
7208 subfeatures = Fcons (Fcons (key, Fcons (val, Qnil)), subfeatures)
7210 #ifdef NON_BLOCKING_CONNECT
7211 ADD_SUBFEATURE (QCnowait, Qt);
7212 #endif
7213 #ifdef DATAGRAM_SOCKETS
7214 ADD_SUBFEATURE (QCtype, Qdatagram);
7215 #endif
7216 #ifdef HAVE_LOCAL_SOCKETS
7217 ADD_SUBFEATURE (QCfamily, Qlocal);
7218 #endif
7219 ADD_SUBFEATURE (QCfamily, Qipv4);
7220 #ifdef AF_INET6
7221 ADD_SUBFEATURE (QCfamily, Qipv6);
7222 #endif
7223 #ifdef HAVE_GETSOCKNAME
7224 ADD_SUBFEATURE (QCservice, Qt);
7225 #endif
7226 #if defined(O_NONBLOCK) || defined(O_NDELAY)
7227 ADD_SUBFEATURE (QCserver, Qt);
7228 #endif
7230 for (sopt = socket_options; sopt->name; sopt++)
7231 subfeatures = Fcons (intern (sopt->name), subfeatures);
7233 Fprovide (intern ("make-network-process"), subfeatures);
7235 #endif /* HAVE_SOCKETS */
7237 #if defined (DARWIN_OS)
7238 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7239 processes. As such, we only change the default value. */
7240 if (initialized)
7242 char *release = get_operating_system_release();
7243 if (!release || !release[0] || (release[0] < MIN_PTY_KERNEL_VERSION
7244 && release[1] == '.')) {
7245 Vprocess_connection_type = Qnil;
7248 #endif
7251 void
7252 syms_of_process ()
7254 Qprocessp = intern ("processp");
7255 staticpro (&Qprocessp);
7256 Qrun = intern ("run");
7257 staticpro (&Qrun);
7258 Qstop = intern ("stop");
7259 staticpro (&Qstop);
7260 Qsignal = intern ("signal");
7261 staticpro (&Qsignal);
7263 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7264 here again.
7266 Qexit = intern ("exit");
7267 staticpro (&Qexit); */
7269 Qopen = intern ("open");
7270 staticpro (&Qopen);
7271 Qclosed = intern ("closed");
7272 staticpro (&Qclosed);
7273 Qconnect = intern ("connect");
7274 staticpro (&Qconnect);
7275 Qfailed = intern ("failed");
7276 staticpro (&Qfailed);
7277 Qlisten = intern ("listen");
7278 staticpro (&Qlisten);
7279 Qlocal = intern ("local");
7280 staticpro (&Qlocal);
7281 Qipv4 = intern ("ipv4");
7282 staticpro (&Qipv4);
7283 #ifdef AF_INET6
7284 Qipv6 = intern ("ipv6");
7285 staticpro (&Qipv6);
7286 #endif
7287 Qdatagram = intern ("datagram");
7288 staticpro (&Qdatagram);
7290 QCport = intern (":port");
7291 staticpro (&QCport);
7292 QCspeed = intern (":speed");
7293 staticpro (&QCspeed);
7294 QCprocess = intern (":process");
7295 staticpro (&QCprocess);
7297 QCbytesize = intern (":bytesize");
7298 staticpro (&QCbytesize);
7299 QCstopbits = intern (":stopbits");
7300 staticpro (&QCstopbits);
7301 QCparity = intern (":parity");
7302 staticpro (&QCparity);
7303 Qodd = intern ("odd");
7304 staticpro (&Qodd);
7305 Qeven = intern ("even");
7306 staticpro (&Qeven);
7307 QCflowcontrol = intern (":flowcontrol");
7308 staticpro (&QCflowcontrol);
7309 Qhw = intern ("hw");
7310 staticpro (&Qhw);
7311 Qsw = intern ("sw");
7312 staticpro (&Qsw);
7313 QCsummary = intern (":summary");
7314 staticpro (&QCsummary);
7316 Qreal = intern ("real");
7317 staticpro (&Qreal);
7318 Qnetwork = intern ("network");
7319 staticpro (&Qnetwork);
7320 Qserial = intern ("serial");
7321 staticpro (&Qserial);
7323 QCname = intern (":name");
7324 staticpro (&QCname);
7325 QCbuffer = intern (":buffer");
7326 staticpro (&QCbuffer);
7327 QChost = intern (":host");
7328 staticpro (&QChost);
7329 QCservice = intern (":service");
7330 staticpro (&QCservice);
7331 QCtype = intern (":type");
7332 staticpro (&QCtype);
7333 QClocal = intern (":local");
7334 staticpro (&QClocal);
7335 QCremote = intern (":remote");
7336 staticpro (&QCremote);
7337 QCcoding = intern (":coding");
7338 staticpro (&QCcoding);
7339 QCserver = intern (":server");
7340 staticpro (&QCserver);
7341 QCnowait = intern (":nowait");
7342 staticpro (&QCnowait);
7343 QCsentinel = intern (":sentinel");
7344 staticpro (&QCsentinel);
7345 QClog = intern (":log");
7346 staticpro (&QClog);
7347 QCnoquery = intern (":noquery");
7348 staticpro (&QCnoquery);
7349 QCstop = intern (":stop");
7350 staticpro (&QCstop);
7351 QCoptions = intern (":options");
7352 staticpro (&QCoptions);
7353 QCplist = intern (":plist");
7354 staticpro (&QCplist);
7356 Qlast_nonmenu_event = intern ("last-nonmenu-event");
7357 staticpro (&Qlast_nonmenu_event);
7359 staticpro (&Vprocess_alist);
7360 #ifdef SIGCHLD
7361 staticpro (&deleted_pid_list);
7362 #endif
7364 Qeuid = intern ("euid");
7365 staticpro (&Qeuid);
7366 Qegid = intern ("egid");
7367 staticpro (&Qegid);
7368 Quser = intern ("user");
7369 staticpro (&Quser);
7370 Qgroup = intern ("group");
7371 staticpro (&Qgroup);
7372 Qcomm = intern ("comm");
7373 staticpro (&Qcomm);
7374 Qstate = intern ("state");
7375 staticpro (&Qstate);
7376 Qppid = intern ("ppid");
7377 staticpro (&Qppid);
7378 Qpgrp = intern ("pgrp");
7379 staticpro (&Qpgrp);
7380 Qsess = intern ("sess");
7381 staticpro (&Qsess);
7382 Qttname = intern ("ttname");
7383 staticpro (&Qttname);
7384 Qtpgid = intern ("tpgid");
7385 staticpro (&Qtpgid);
7386 Qminflt = intern ("minflt");
7387 staticpro (&Qminflt);
7388 Qmajflt = intern ("majflt");
7389 staticpro (&Qmajflt);
7390 Qcminflt = intern ("cminflt");
7391 staticpro (&Qcminflt);
7392 Qcmajflt = intern ("cmajflt");
7393 staticpro (&Qcmajflt);
7394 Qutime = intern ("utime");
7395 staticpro (&Qutime);
7396 Qstime = intern ("stime");
7397 staticpro (&Qstime);
7398 Qtime = intern ("time");
7399 staticpro (&Qtime);
7400 Qcutime = intern ("cutime");
7401 staticpro (&Qcutime);
7402 Qcstime = intern ("cstime");
7403 staticpro (&Qcstime);
7404 Qctime = intern ("ctime");
7405 staticpro (&Qctime);
7406 Qpri = intern ("pri");
7407 staticpro (&Qpri);
7408 Qnice = intern ("nice");
7409 staticpro (&Qnice);
7410 Qthcount = intern ("thcount");
7411 staticpro (&Qthcount);
7412 Qstart = intern ("start");
7413 staticpro (&Qstart);
7414 Qvsize = intern ("vsize");
7415 staticpro (&Qvsize);
7416 Qrss = intern ("rss");
7417 staticpro (&Qrss);
7418 Qetime = intern ("etime");
7419 staticpro (&Qetime);
7420 Qpcpu = intern ("pcpu");
7421 staticpro (&Qpcpu);
7422 Qpmem = intern ("pmem");
7423 staticpro (&Qpmem);
7424 Qargs = intern ("args");
7425 staticpro (&Qargs);
7427 DEFVAR_BOOL ("delete-exited-processes", &delete_exited_processes,
7428 doc: /* *Non-nil means delete processes immediately when they exit.
7429 A value of nil means don't delete them until `list-processes' is run. */);
7431 delete_exited_processes = 1;
7433 DEFVAR_LISP ("process-connection-type", &Vprocess_connection_type,
7434 doc: /* Control type of device used to communicate with subprocesses.
7435 Values are nil to use a pipe, or t or `pty' to use a pty.
7436 The value has no effect if the system has no ptys or if all ptys are busy:
7437 then a pipe is used in any case.
7438 The value takes effect when `start-process' is called. */);
7439 Vprocess_connection_type = Qt;
7441 #ifdef ADAPTIVE_READ_BUFFERING
7442 DEFVAR_LISP ("process-adaptive-read-buffering", &Vprocess_adaptive_read_buffering,
7443 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7444 On some systems, when Emacs reads the output from a subprocess, the output data
7445 is read in very small blocks, potentially resulting in very poor performance.
7446 This behavior can be remedied to some extent by setting this variable to a
7447 non-nil value, as it will automatically delay reading from such processes, to
7448 allow them to produce more output before Emacs tries to read it.
7449 If the value is t, the delay is reset after each write to the process; any other
7450 non-nil value means that the delay is not reset on write.
7451 The variable takes effect when `start-process' is called. */);
7452 Vprocess_adaptive_read_buffering = Qt;
7453 #endif
7455 defsubr (&Sprocessp);
7456 defsubr (&Sget_process);
7457 defsubr (&Sget_buffer_process);
7458 defsubr (&Sdelete_process);
7459 defsubr (&Sprocess_status);
7460 defsubr (&Sprocess_exit_status);
7461 defsubr (&Sprocess_id);
7462 defsubr (&Sprocess_name);
7463 defsubr (&Sprocess_tty_name);
7464 defsubr (&Sprocess_command);
7465 defsubr (&Sset_process_buffer);
7466 defsubr (&Sprocess_buffer);
7467 defsubr (&Sprocess_mark);
7468 defsubr (&Sset_process_filter);
7469 defsubr (&Sprocess_filter);
7470 defsubr (&Sset_process_sentinel);
7471 defsubr (&Sprocess_sentinel);
7472 defsubr (&Sset_process_window_size);
7473 defsubr (&Sset_process_inherit_coding_system_flag);
7474 defsubr (&Sprocess_inherit_coding_system_flag);
7475 defsubr (&Sset_process_query_on_exit_flag);
7476 defsubr (&Sprocess_query_on_exit_flag);
7477 defsubr (&Sprocess_contact);
7478 defsubr (&Sprocess_plist);
7479 defsubr (&Sset_process_plist);
7480 defsubr (&Slist_processes);
7481 defsubr (&Sprocess_list);
7482 defsubr (&Sstart_process);
7483 #ifdef HAVE_SERIAL
7484 defsubr (&Sserial_process_configure);
7485 defsubr (&Smake_serial_process);
7486 #endif /* HAVE_SERIAL */
7487 #ifdef HAVE_SOCKETS
7488 defsubr (&Sset_network_process_option);
7489 defsubr (&Smake_network_process);
7490 defsubr (&Sformat_network_address);
7491 #endif /* HAVE_SOCKETS */
7492 #if defined(HAVE_SOCKETS) && defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
7493 #ifdef SIOCGIFCONF
7494 defsubr (&Snetwork_interface_list);
7495 #endif
7496 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
7497 defsubr (&Snetwork_interface_info);
7498 #endif
7499 #endif /* HAVE_SOCKETS ... */
7500 #ifdef DATAGRAM_SOCKETS
7501 defsubr (&Sprocess_datagram_address);
7502 defsubr (&Sset_process_datagram_address);
7503 #endif
7504 defsubr (&Saccept_process_output);
7505 defsubr (&Sprocess_send_region);
7506 defsubr (&Sprocess_send_string);
7507 defsubr (&Sinterrupt_process);
7508 defsubr (&Skill_process);
7509 defsubr (&Squit_process);
7510 defsubr (&Sstop_process);
7511 defsubr (&Scontinue_process);
7512 defsubr (&Sprocess_running_child_p);
7513 defsubr (&Sprocess_send_eof);
7514 defsubr (&Ssignal_process);
7515 defsubr (&Swaiting_for_user_input_p);
7516 defsubr (&Sprocess_type);
7517 defsubr (&Sset_process_coding_system);
7518 defsubr (&Sprocess_coding_system);
7519 defsubr (&Sset_process_filter_multibyte);
7520 defsubr (&Sprocess_filter_multibyte_p);
7521 defsubr (&Slist_system_processes);
7522 defsubr (&Sprocess_attributes);
7526 #else /* not subprocesses */
7528 #include <sys/types.h>
7529 #include <errno.h>
7530 #include <sys/stat.h>
7531 #include <stdlib.h>
7532 #include <fcntl.h>
7533 #ifdef HAVE_UNISTD_H
7534 #include <unistd.h>
7535 #endif
7537 #include "lisp.h"
7538 #include "systime.h"
7539 #include "character.h"
7540 #include "coding.h"
7541 #include "termopts.h"
7542 #include "sysselect.h"
7544 extern int frame_garbaged;
7546 extern EMACS_TIME timer_check ();
7547 extern int timers_run;
7549 Lisp_Object QCtype, QCname;
7551 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
7552 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
7553 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
7554 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
7556 /* As described above, except assuming that there are no subprocesses:
7558 Wait for timeout to elapse and/or keyboard input to be available.
7560 time_limit is:
7561 timeout in seconds, or
7562 zero for no limit, or
7563 -1 means gobble data immediately available but don't wait for any.
7565 read_kbd is a Lisp_Object:
7566 0 to ignore keyboard input, or
7567 1 to return when input is available, or
7568 -1 means caller will actually read the input, so don't throw to
7569 the quit handler.
7571 see full version for other parameters. We know that wait_proc will
7572 always be NULL, since `subprocesses' isn't defined.
7574 do_display != 0 means redisplay should be done to show subprocess
7575 output that arrives.
7577 Return true if we received input from any process. */
7580 wait_reading_process_output (time_limit, microsecs, read_kbd, do_display,
7581 wait_for_cell, wait_proc, just_wait_proc)
7582 int time_limit, microsecs, read_kbd, do_display;
7583 Lisp_Object wait_for_cell;
7584 struct Lisp_Process *wait_proc;
7585 int just_wait_proc;
7587 register int nfds;
7588 EMACS_TIME end_time, timeout;
7589 SELECT_TYPE waitchannels;
7590 int xerrno;
7592 /* What does time_limit really mean? */
7593 if (time_limit || microsecs)
7595 EMACS_GET_TIME (end_time);
7596 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
7597 EMACS_ADD_TIME (end_time, end_time, timeout);
7600 /* Turn off periodic alarms (in case they are in use)
7601 and then turn off any other atimers,
7602 because the select emulator uses alarms. */
7603 stop_polling ();
7604 turn_on_atimers (0);
7606 while (1)
7608 int timeout_reduced_for_timers = 0;
7610 /* If calling from keyboard input, do not quit
7611 since we want to return C-g as an input character.
7612 Otherwise, do pending quit if requested. */
7613 if (read_kbd >= 0)
7614 QUIT;
7616 /* Exit now if the cell we're waiting for became non-nil. */
7617 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7618 break;
7620 /* Compute time from now till when time limit is up */
7621 /* Exit if already run out */
7622 if (time_limit == -1)
7624 /* -1 specified for timeout means
7625 gobble output available now
7626 but don't wait at all. */
7628 EMACS_SET_SECS_USECS (timeout, 0, 0);
7630 else if (time_limit || microsecs)
7632 EMACS_GET_TIME (timeout);
7633 EMACS_SUB_TIME (timeout, end_time, timeout);
7634 if (EMACS_TIME_NEG_P (timeout))
7635 break;
7637 else
7639 EMACS_SET_SECS_USECS (timeout, 100000, 0);
7642 /* If our caller will not immediately handle keyboard events,
7643 run timer events directly.
7644 (Callers that will immediately read keyboard events
7645 call timer_delay on their own.) */
7646 if (NILP (wait_for_cell))
7648 EMACS_TIME timer_delay;
7652 int old_timers_run = timers_run;
7653 timer_delay = timer_check (1);
7654 if (timers_run != old_timers_run && do_display)
7655 /* We must retry, since a timer may have requeued itself
7656 and that could alter the time delay. */
7657 redisplay_preserve_echo_area (14);
7658 else
7659 break;
7661 while (!detect_input_pending ());
7663 /* If there is unread keyboard input, also return. */
7664 if (read_kbd != 0
7665 && requeued_events_pending_p ())
7666 break;
7668 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
7670 EMACS_TIME difference;
7671 EMACS_SUB_TIME (difference, timer_delay, timeout);
7672 if (EMACS_TIME_NEG_P (difference))
7674 timeout = timer_delay;
7675 timeout_reduced_for_timers = 1;
7680 /* Cause C-g and alarm signals to take immediate action,
7681 and cause input available signals to zero out timeout. */
7682 if (read_kbd < 0)
7683 set_waiting_for_input (&timeout);
7685 /* Wait till there is something to do. */
7687 if (! read_kbd && NILP (wait_for_cell))
7688 FD_ZERO (&waitchannels);
7689 else
7690 FD_SET (0, &waitchannels);
7692 /* If a frame has been newly mapped and needs updating,
7693 reprocess its display stuff. */
7694 if (frame_garbaged && do_display)
7696 clear_waiting_for_input ();
7697 redisplay_preserve_echo_area (15);
7698 if (read_kbd < 0)
7699 set_waiting_for_input (&timeout);
7702 if (read_kbd && detect_input_pending ())
7704 nfds = 0;
7705 FD_ZERO (&waitchannels);
7707 else
7708 nfds = select (1, &waitchannels, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
7709 &timeout);
7711 xerrno = errno;
7713 /* Make C-g and alarm signals set flags again */
7714 clear_waiting_for_input ();
7716 /* If we woke up due to SIGWINCH, actually change size now. */
7717 do_pending_window_change (0);
7719 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
7720 /* We waited the full specified time, so return now. */
7721 break;
7723 if (nfds == -1)
7725 /* If the system call was interrupted, then go around the
7726 loop again. */
7727 if (xerrno == EINTR)
7728 FD_ZERO (&waitchannels);
7729 else
7730 error ("select error: %s", emacs_strerror (xerrno));
7732 #ifdef SOLARIS2
7733 else if (nfds > 0 && (waitchannels & 1) && interrupt_input)
7734 /* System sometimes fails to deliver SIGIO. */
7735 kill (getpid (), SIGIO);
7736 #endif
7737 #ifdef SIGIO
7738 if (read_kbd && interrupt_input && (waitchannels & 1))
7739 kill (getpid (), SIGIO);
7740 #endif
7742 /* Check for keyboard input */
7744 if (read_kbd
7745 && detect_input_pending_run_timers (do_display))
7747 swallow_events (do_display);
7748 if (detect_input_pending_run_timers (do_display))
7749 break;
7752 /* If there is unread keyboard input, also return. */
7753 if (read_kbd
7754 && requeued_events_pending_p ())
7755 break;
7757 /* If wait_for_cell. check for keyboard input
7758 but don't run any timers.
7759 ??? (It seems wrong to me to check for keyboard
7760 input at all when wait_for_cell, but the code
7761 has been this way since July 1994.
7762 Try changing this after version 19.31.) */
7763 if (! NILP (wait_for_cell)
7764 && detect_input_pending ())
7766 swallow_events (do_display);
7767 if (detect_input_pending ())
7768 break;
7771 /* Exit now if the cell we're waiting for became non-nil. */
7772 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7773 break;
7776 start_polling ();
7778 return 0;
7782 /* Don't confuse make-docfile by having two doc strings for this function.
7783 make-docfile does not pay attention to #if, for good reason! */
7784 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7786 (name)
7787 register Lisp_Object name;
7789 return Qnil;
7792 /* Don't confuse make-docfile by having two doc strings for this function.
7793 make-docfile does not pay attention to #if, for good reason! */
7794 DEFUN ("process-inherit-coding-system-flag",
7795 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7796 1, 1, 0,
7798 (process)
7799 register Lisp_Object process;
7801 /* Ignore the argument and return the value of
7802 inherit-process-coding-system. */
7803 return inherit_process_coding_system ? Qt : Qnil;
7806 /* Kill all processes associated with `buffer'.
7807 If `buffer' is nil, kill all processes.
7808 Since we have no subprocesses, this does nothing. */
7810 void
7811 kill_buffer_processes (buffer)
7812 Lisp_Object buffer;
7816 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7817 0, 0, 0,
7818 doc: /* Return a list of numerical process IDs of all running processes.
7819 If this functionality is unsupported, return nil.
7821 See `process-attributes' for getting attributes of a process given its ID. */)
7824 return list_system_processes ();
7827 DEFUN ("process-attributes", Fprocess_attributes,
7828 Sprocess_attributes, 1, 1, 0,
7829 doc: /* Return attributes of the process given by its PID, a number.
7831 Value is an alist where each element is a cons cell of the form
7833 \(KEY . VALUE)
7835 If this functionality is unsupported, the value is nil.
7837 See `list-system-processes' for getting a list of all process IDs.
7839 The KEYs of the attributes that this function may return are listed
7840 below, together with the type of the associated VALUE (in parentheses).
7841 Not all platforms support all of these attributes; unsupported
7842 attributes will not appear in the returned alist.
7843 Unless explicitly indicated otherwise, numbers can have either
7844 integer or floating point values.
7846 euid -- Effective user User ID of the process (number)
7847 user -- User name corresponding to euid (string)
7848 egid -- Effective user Group ID of the process (number)
7849 group -- Group name corresponding to egid (string)
7850 comm -- Command name (executable name only) (string)
7851 state -- Process state code, such as "S", "R", or "T" (string)
7852 ppid -- Parent process ID (number)
7853 pgrp -- Process group ID (number)
7854 sess -- Session ID, i.e. process ID of session leader (number)
7855 ttname -- Controlling tty name (string)
7856 tpgid -- ID of foreground process group on the process's tty (number)
7857 minflt -- number of minor page faults (number)
7858 majflt -- number of major page faults (number)
7859 cminflt -- cumulative number of minor page faults (number)
7860 cmajflt -- cumulative number of major page faults (number)
7861 utime -- user time used by the process, in the (HIGH LOW USEC) format
7862 stime -- system time used by the process, in the (HIGH LOW USEC) format
7863 time -- sum of utime and stime, in the (HIGH LOW USEC) format
7864 cutime -- user time used by the process and its children, (HIGH LOW USEC)
7865 cstime -- system time used by the process and its children, (HIGH LOW USEC)
7866 ctime -- sum of cutime and cstime, in the (HIGH LOW USEC) format
7867 pri -- priority of the process (number)
7868 nice -- nice value of the process (number)
7869 thcount -- process thread count (number)
7870 start -- time the process started, in the (HIGH LOW USEC) format
7871 vsize -- virtual memory size of the process in KB's (number)
7872 rss -- resident set size of the process in KB's (number)
7873 etime -- elapsed time the process is running, in (HIGH LOW USEC) format
7874 pcpu -- percents of CPU time used by the process (floating-point number)
7875 pmem -- percents of total physical memory used by process's resident set
7876 (floating-point number)
7877 args -- command line which invoked the process (string). */)
7878 (pid)
7880 Lisp_Object pid;
7882 return system_process_attributes (pid);
7885 void
7886 init_process ()
7890 void
7891 syms_of_process ()
7893 QCtype = intern (":type");
7894 staticpro (&QCtype);
7895 QCname = intern (":name");
7896 staticpro (&QCname);
7897 QCtype = intern (":type");
7898 staticpro (&QCtype);
7899 QCname = intern (":name");
7900 staticpro (&QCname);
7901 Qeuid = intern ("euid");
7902 staticpro (&Qeuid);
7903 Qegid = intern ("egid");
7904 staticpro (&Qegid);
7905 Quser = intern ("user");
7906 staticpro (&Quser);
7907 Qgroup = intern ("group");
7908 staticpro (&Qgroup);
7909 Qcomm = intern ("comm");
7910 staticpro (&Qcomm);
7911 Qstate = intern ("state");
7912 staticpro (&Qstate);
7913 Qppid = intern ("ppid");
7914 staticpro (&Qppid);
7915 Qpgrp = intern ("pgrp");
7916 staticpro (&Qpgrp);
7917 Qsess = intern ("sess");
7918 staticpro (&Qsess);
7919 Qttname = intern ("ttname");
7920 staticpro (&Qttname);
7921 Qtpgid = intern ("tpgid");
7922 staticpro (&Qtpgid);
7923 Qminflt = intern ("minflt");
7924 staticpro (&Qminflt);
7925 Qmajflt = intern ("majflt");
7926 staticpro (&Qmajflt);
7927 Qcminflt = intern ("cminflt");
7928 staticpro (&Qcminflt);
7929 Qcmajflt = intern ("cmajflt");
7930 staticpro (&Qcmajflt);
7931 Qutime = intern ("utime");
7932 staticpro (&Qutime);
7933 Qstime = intern ("stime");
7934 staticpro (&Qstime);
7935 Qtime = intern ("time");
7936 staticpro (&Qtime);
7937 Qcutime = intern ("cutime");
7938 staticpro (&Qcutime);
7939 Qcstime = intern ("cstime");
7940 staticpro (&Qcstime);
7941 Qctime = intern ("ctime");
7942 staticpro (&Qctime);
7943 Qpri = intern ("pri");
7944 staticpro (&Qpri);
7945 Qnice = intern ("nice");
7946 staticpro (&Qnice);
7947 Qthcount = intern ("thcount");
7948 staticpro (&Qthcount);
7949 Qstart = intern ("start");
7950 staticpro (&Qstart);
7951 Qvsize = intern ("vsize");
7952 staticpro (&Qvsize);
7953 Qrss = intern ("rss");
7954 staticpro (&Qrss);
7955 Qetime = intern ("etime");
7956 staticpro (&Qetime);
7957 Qpcpu = intern ("pcpu");
7958 staticpro (&Qpcpu);
7959 Qpmem = intern ("pmem");
7960 staticpro (&Qpmem);
7961 Qargs = intern ("args");
7962 staticpro (&Qargs);
7964 defsubr (&Sget_buffer_process);
7965 defsubr (&Sprocess_inherit_coding_system_flag);
7966 defsubr (&Slist_system_processes);
7967 defsubr (&Sprocess_attributes);
7971 #endif /* not subprocesses */
7973 /* arch-tag: 3706c011-7b9a-4117-bd4f-59e7f701a4c4
7974 (do not change this comment) */