src/xdisp.c (single_display_spec_string): Correct a FIXME comment.
[emacs.git] / src / process.c
blob8a94b3e6047e859e7a20ed7d7be9523d1aa6a039
1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2011
4 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>
24 #include <stdio.h>
25 #include <errno.h>
26 #include <setjmp.h>
27 #include <sys/types.h> /* Some typedefs are used in sys/file.h. */
28 #include <sys/file.h>
29 #include <sys/stat.h>
30 #include <setjmp.h>
32 #include <unistd.h>
33 #include <fcntl.h>
35 #include "lisp.h"
37 /* Only MS-DOS does not define `subprocesses'. */
38 #ifdef subprocesses
40 #include <sys/socket.h>
41 #include <netdb.h>
42 #include <netinet/in.h>
43 #include <arpa/inet.h>
45 /* Are local (unix) sockets supported? */
46 #if defined (HAVE_SYS_UN_H)
47 #if !defined (AF_LOCAL) && defined (AF_UNIX)
48 #define AF_LOCAL AF_UNIX
49 #endif
50 #ifdef AF_LOCAL
51 #define HAVE_LOCAL_SOCKETS
52 #include <sys/un.h>
53 #endif
54 #endif
56 #include <sys/ioctl.h>
57 #if defined(HAVE_NET_IF_H)
58 #include <net/if.h>
59 #endif /* HAVE_NET_IF_H */
61 #ifdef NEED_BSDTTY
62 #include <bsdtty.h>
63 #endif
65 #ifdef HAVE_RES_INIT
66 #include <netinet/in.h>
67 #include <arpa/nameser.h>
68 #include <resolv.h>
69 #endif
71 #ifdef HAVE_UTIL_H
72 #include <util.h>
73 #endif
75 #ifdef HAVE_PTY_H
76 #include <pty.h>
77 #endif
79 #endif /* subprocesses */
81 #include "systime.h"
82 #include "systty.h"
84 #include "window.h"
85 #include "buffer.h"
86 #include "character.h"
87 #include "coding.h"
88 #include "process.h"
89 #include "frame.h"
90 #include "termhooks.h"
91 #include "termopts.h"
92 #include "commands.h"
93 #include "keyboard.h"
94 #include "blockinput.h"
95 #include "dispextern.h"
96 #include "composite.h"
97 #include "atimer.h"
98 #include "sysselect.h"
99 #include "syssignal.h"
100 #include "syswait.h"
101 #ifdef HAVE_GNUTLS
102 #include "gnutls.h"
103 #endif
105 #if defined (USE_GTK) || defined (HAVE_GCONF)
106 #include "xgselect.h"
107 #endif /* defined (USE_GTK) || defined (HAVE_GCONF) */
108 #ifdef HAVE_NS
109 #include "nsterm.h"
110 #endif
112 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
113 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
114 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
115 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
116 Lisp_Object QCname, QCtype;
118 /* Non-zero if keyboard input is on hold, zero otherwise. */
120 static int kbd_is_on_hold;
122 /* Nonzero means don't run process sentinels. This is used
123 when exiting. */
124 int inhibit_sentinels;
126 #ifdef subprocesses
128 Lisp_Object Qprocessp;
129 static Lisp_Object Qrun, Qstop, Qsignal;
130 static Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
131 Lisp_Object Qlocal;
132 static Lisp_Object Qipv4, Qdatagram, Qseqpacket;
133 static Lisp_Object Qreal, Qnetwork, Qserial;
134 #ifdef AF_INET6
135 static Lisp_Object Qipv6;
136 #endif
137 static Lisp_Object QCport, QCprocess;
138 Lisp_Object QCspeed;
139 Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
140 Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
141 static Lisp_Object QCbuffer, QChost, QCservice;
142 static Lisp_Object QClocal, QCremote, QCcoding;
143 static Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
144 static Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
145 static Lisp_Object Qlast_nonmenu_event;
146 /* QCfamily is declared and initialized in xfaces.c,
147 QCfilter in keyboard.c. */
148 extern Lisp_Object QCfamily, QCfilter;
150 /* Qexit is declared and initialized in eval.c. */
152 /* QCfamily is defined in xfaces.c. */
153 extern Lisp_Object QCfamily;
154 /* QCfilter is defined in keyboard.c. */
155 extern Lisp_Object QCfilter;
157 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
158 #define NETCONN1_P(p) (EQ ((p)->type, Qnetwork))
159 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
160 #define SERIALCONN1_P(p) (EQ ((p)->type, Qserial))
162 #ifndef HAVE_H_ERRNO
163 extern int h_errno;
164 #endif
166 /* Number of events of change of status of a process. */
167 static int process_tick;
168 /* Number of events for which the user or sentinel has been notified. */
169 static int update_tick;
171 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
173 /* Only W32 has this, it really means that select can't take write mask. */
174 #ifdef BROKEN_NON_BLOCKING_CONNECT
175 #undef NON_BLOCKING_CONNECT
176 #define SELECT_CANT_DO_WRITE_MASK
177 #else
178 #ifndef NON_BLOCKING_CONNECT
179 #ifdef HAVE_SELECT
180 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
181 #if defined (O_NONBLOCK) || defined (O_NDELAY)
182 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
183 #define NON_BLOCKING_CONNECT
184 #endif /* EWOULDBLOCK || EINPROGRESS */
185 #endif /* O_NONBLOCK || O_NDELAY */
186 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
187 #endif /* HAVE_SELECT */
188 #endif /* NON_BLOCKING_CONNECT */
189 #endif /* BROKEN_NON_BLOCKING_CONNECT */
191 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
192 this system. We need to read full packets, so we need a
193 "non-destructive" select. So we require either native select,
194 or emulation of select using FIONREAD. */
196 #ifdef BROKEN_DATAGRAM_SOCKETS
197 #undef DATAGRAM_SOCKETS
198 #else
199 #ifndef DATAGRAM_SOCKETS
200 #if defined (HAVE_SELECT) || defined (FIONREAD)
201 #if defined (HAVE_SENDTO) && defined (HAVE_RECVFROM) && defined (EMSGSIZE)
202 #define DATAGRAM_SOCKETS
203 #endif /* HAVE_SENDTO && HAVE_RECVFROM && EMSGSIZE */
204 #endif /* HAVE_SELECT || FIONREAD */
205 #endif /* DATAGRAM_SOCKETS */
206 #endif /* BROKEN_DATAGRAM_SOCKETS */
208 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
209 # define HAVE_SEQPACKET
210 #endif
212 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
213 #ifdef EMACS_HAS_USECS
214 #define ADAPTIVE_READ_BUFFERING
215 #endif
216 #endif
218 #ifdef ADAPTIVE_READ_BUFFERING
219 #define READ_OUTPUT_DELAY_INCREMENT 10000
220 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
221 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
223 /* Number of processes which have a non-zero read_output_delay,
224 and therefore might be delayed for adaptive read buffering. */
226 static int process_output_delay_count;
228 /* Non-zero if any process has non-nil read_output_skip. */
230 static int process_output_skip;
232 #else
233 #define process_output_delay_count 0
234 #endif
236 static Lisp_Object Fget_process (Lisp_Object);
237 static void create_process (Lisp_Object, char **, Lisp_Object);
238 #ifdef SIGIO
239 static int keyboard_bit_set (SELECT_TYPE *);
240 #endif
241 static void deactivate_process (Lisp_Object);
242 static void status_notify (struct Lisp_Process *);
243 static int read_process_output (Lisp_Object, int);
244 static void create_pty (Lisp_Object);
246 /* If we support a window system, turn on the code to poll periodically
247 to detect C-g. It isn't actually used when doing interrupt input. */
248 #ifdef HAVE_WINDOW_SYSTEM
249 #define POLL_FOR_INPUT
250 #endif
252 static Lisp_Object get_process (register Lisp_Object name);
253 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
255 /* Mask of bits indicating the descriptors that we wait for input on. */
257 static SELECT_TYPE input_wait_mask;
259 /* Mask that excludes keyboard input descriptor(s). */
261 static SELECT_TYPE non_keyboard_wait_mask;
263 /* Mask that excludes process input descriptor(s). */
265 static SELECT_TYPE non_process_wait_mask;
267 /* Mask for selecting for write. */
269 static SELECT_TYPE write_mask;
271 #ifdef NON_BLOCKING_CONNECT
272 /* Mask of bits indicating the descriptors that we wait for connect to
273 complete on. Once they complete, they are removed from this mask
274 and added to the input_wait_mask and non_keyboard_wait_mask. */
276 static SELECT_TYPE connect_wait_mask;
278 /* Number of bits set in connect_wait_mask. */
279 static int num_pending_connects;
280 #endif /* NON_BLOCKING_CONNECT */
282 /* The largest descriptor currently in use for a process object. */
283 static int max_process_desc;
285 /* The largest descriptor currently in use for input. */
286 static int max_input_desc;
288 /* Indexed by descriptor, gives the process (if any) for that descriptor */
289 static Lisp_Object chan_process[MAXDESC];
291 /* Alist of elements (NAME . PROCESS) */
292 static Lisp_Object Vprocess_alist;
294 /* Buffered-ahead input char from process, indexed by channel.
295 -1 means empty (no char is buffered).
296 Used on sys V where the only way to tell if there is any
297 output from the process is to read at least one char.
298 Always -1 on systems that support FIONREAD. */
300 static int proc_buffered_char[MAXDESC];
302 /* Table of `struct coding-system' for each process. */
303 static struct coding_system *proc_decode_coding_system[MAXDESC];
304 static struct coding_system *proc_encode_coding_system[MAXDESC];
306 #ifdef DATAGRAM_SOCKETS
307 /* Table of `partner address' for datagram sockets. */
308 static struct sockaddr_and_len {
309 struct sockaddr *sa;
310 int len;
311 } datagram_address[MAXDESC];
312 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
313 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
314 #else
315 #define DATAGRAM_CHAN_P(chan) (0)
316 #define DATAGRAM_CONN_P(proc) (0)
317 #endif
319 /* Maximum number of bytes to send to a pty without an eof. */
320 static int pty_max_bytes;
324 static struct fd_callback_data
326 fd_callback func;
327 void *data;
328 #define FOR_READ 1
329 #define FOR_WRITE 2
330 int condition; /* mask of the defines above. */
331 } fd_callback_info[MAXDESC];
334 /* Add a file descriptor FD to be monitored for when read is possible.
335 When read is possible, call FUNC with argument DATA. */
337 void
338 add_read_fd (int fd, fd_callback func, void *data)
340 xassert (fd < MAXDESC);
341 add_keyboard_wait_descriptor (fd);
343 fd_callback_info[fd].func = func;
344 fd_callback_info[fd].data = data;
345 fd_callback_info[fd].condition |= FOR_READ;
348 /* Stop monitoring file descriptor FD for when read is possible. */
350 void
351 delete_read_fd (int fd)
353 xassert (fd < MAXDESC);
354 delete_keyboard_wait_descriptor (fd);
356 fd_callback_info[fd].condition &= ~FOR_READ;
357 if (fd_callback_info[fd].condition == 0)
359 fd_callback_info[fd].func = 0;
360 fd_callback_info[fd].data = 0;
364 /* Add a file descriptor FD to be monitored for when write is possible.
365 When write is possible, call FUNC with argument DATA. */
367 void
368 add_write_fd (int fd, fd_callback func, void *data)
370 xassert (fd < MAXDESC);
371 FD_SET (fd, &write_mask);
372 if (fd > max_input_desc)
373 max_input_desc = fd;
375 fd_callback_info[fd].func = func;
376 fd_callback_info[fd].data = data;
377 fd_callback_info[fd].condition |= FOR_WRITE;
380 /* Stop monitoring file descriptor FD for when write is possible. */
382 void
383 delete_write_fd (int fd)
385 int lim = max_input_desc;
387 xassert (fd < MAXDESC);
388 FD_CLR (fd, &write_mask);
389 fd_callback_info[fd].condition &= ~FOR_WRITE;
390 if (fd_callback_info[fd].condition == 0)
392 fd_callback_info[fd].func = 0;
393 fd_callback_info[fd].data = 0;
395 if (fd == max_input_desc)
396 for (fd = lim; fd >= 0; fd--)
397 if (FD_ISSET (fd, &input_wait_mask) || FD_ISSET (fd, &write_mask))
399 max_input_desc = fd;
400 break;
407 /* Compute the Lisp form of the process status, p->status, from
408 the numeric status that was returned by `wait'. */
410 static Lisp_Object status_convert (int);
412 static void
413 update_status (struct Lisp_Process *p)
415 eassert (p->raw_status_new);
416 p->status = status_convert (p->raw_status);
417 p->raw_status_new = 0;
420 /* Convert a process status word in Unix format to
421 the list that we use internally. */
423 static Lisp_Object
424 status_convert (int w)
426 if (WIFSTOPPED (w))
427 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
428 else if (WIFEXITED (w))
429 return Fcons (Qexit, Fcons (make_number (WRETCODE (w)),
430 WCOREDUMP (w) ? Qt : Qnil));
431 else if (WIFSIGNALED (w))
432 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
433 WCOREDUMP (w) ? Qt : Qnil));
434 else
435 return Qrun;
438 /* Given a status-list, extract the three pieces of information
439 and store them individually through the three pointers. */
441 static void
442 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, int *coredump)
444 Lisp_Object tem;
446 if (SYMBOLP (l))
448 *symbol = l;
449 *code = 0;
450 *coredump = 0;
452 else
454 *symbol = XCAR (l);
455 tem = XCDR (l);
456 *code = XFASTINT (XCAR (tem));
457 tem = XCDR (tem);
458 *coredump = !NILP (tem);
462 /* Return a string describing a process status list. */
464 static Lisp_Object
465 status_message (struct Lisp_Process *p)
467 Lisp_Object status = p->status;
468 Lisp_Object symbol;
469 int code, coredump;
470 Lisp_Object string, string2;
472 decode_status (status, &symbol, &code, &coredump);
474 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
476 char *signame;
477 synchronize_system_messages_locale ();
478 signame = strsignal (code);
479 if (signame == 0)
480 string = build_string ("unknown");
481 else
483 int c1, c2;
485 string = make_unibyte_string (signame, strlen (signame));
486 if (! NILP (Vlocale_coding_system))
487 string = (code_convert_string_norecord
488 (string, Vlocale_coding_system, 0));
489 c1 = STRING_CHAR (SDATA (string));
490 c2 = downcase (c1);
491 if (c1 != c2)
492 Faset (string, make_number (0), make_number (c2));
494 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
495 return concat2 (string, string2);
497 else if (EQ (symbol, Qexit))
499 if (NETCONN1_P (p))
500 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
501 if (code == 0)
502 return build_string ("finished\n");
503 string = Fnumber_to_string (make_number (code));
504 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
505 return concat3 (build_string ("exited abnormally with code "),
506 string, string2);
508 else if (EQ (symbol, Qfailed))
510 string = Fnumber_to_string (make_number (code));
511 string2 = build_string ("\n");
512 return concat3 (build_string ("failed with code "),
513 string, string2);
515 else
516 return Fcopy_sequence (Fsymbol_name (symbol));
519 #ifdef HAVE_PTYS
521 /* The file name of the pty opened by allocate_pty. */
522 static char pty_name[24];
524 /* Open an available pty, returning a file descriptor.
525 Return -1 on failure.
526 The file name of the terminal corresponding to the pty
527 is left in the variable pty_name. */
529 static int
530 allocate_pty (void)
532 int fd;
534 #ifdef PTY_ITERATION
535 PTY_ITERATION
536 #else
537 register int c, i;
538 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
539 for (i = 0; i < 16; i++)
540 #endif
542 #ifdef PTY_NAME_SPRINTF
543 PTY_NAME_SPRINTF
544 #else
545 sprintf (pty_name, "/dev/pty%c%x", c, i);
546 #endif /* no PTY_NAME_SPRINTF */
548 #ifdef PTY_OPEN
549 PTY_OPEN;
550 #else /* no PTY_OPEN */
552 { /* Some systems name their pseudoterminals so that there are gaps in
553 the usual sequence - for example, on HP9000/S700 systems, there
554 are no pseudoterminals with names ending in 'f'. So we wait for
555 three failures in a row before deciding that we've reached the
556 end of the ptys. */
557 int failed_count = 0;
558 struct stat stb;
560 if (stat (pty_name, &stb) < 0)
562 failed_count++;
563 if (failed_count >= 3)
564 return -1;
566 else
567 failed_count = 0;
569 # ifdef O_NONBLOCK
570 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
571 # else
572 fd = emacs_open (pty_name, O_RDWR | O_NDELAY, 0);
573 # endif
575 #endif /* no PTY_OPEN */
577 if (fd >= 0)
579 /* check to make certain that both sides are available
580 this avoids a nasty yet stupid bug in rlogins */
581 #ifdef PTY_TTY_NAME_SPRINTF
582 PTY_TTY_NAME_SPRINTF
583 #else
584 sprintf (pty_name, "/dev/tty%c%x", c, i);
585 #endif /* no PTY_TTY_NAME_SPRINTF */
586 if (access (pty_name, 6) != 0)
588 emacs_close (fd);
589 # ifndef __sgi
590 continue;
591 # else
592 return -1;
593 # endif /* __sgi */
595 setup_pty (fd);
596 return fd;
599 return -1;
601 #endif /* HAVE_PTYS */
603 static Lisp_Object
604 make_process (Lisp_Object name)
606 register Lisp_Object val, tem, name1;
607 register struct Lisp_Process *p;
608 char suffix[10];
609 register int i;
611 p = allocate_process ();
613 p->infd = -1;
614 p->outfd = -1;
615 p->tick = 0;
616 p->update_tick = 0;
617 p->pid = 0;
618 p->pty_flag = 0;
619 p->raw_status_new = 0;
620 p->status = Qrun;
621 p->mark = Fmake_marker ();
622 p->kill_without_query = 0;
624 #ifdef ADAPTIVE_READ_BUFFERING
625 p->adaptive_read_buffering = 0;
626 p->read_output_delay = 0;
627 p->read_output_skip = 0;
628 #endif
630 #ifdef HAVE_GNUTLS
631 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
632 p->gnutls_log_level = 0;
633 p->gnutls_p = 0;
634 #endif
636 /* If name is already in use, modify it until it is unused. */
638 name1 = name;
639 for (i = 1; ; i++)
641 tem = Fget_process (name1);
642 if (NILP (tem)) break;
643 sprintf (suffix, "<%d>", i);
644 name1 = concat2 (name, build_string (suffix));
646 name = name1;
647 p->name = name;
648 XSETPROCESS (val, p);
649 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
650 return val;
653 static void
654 remove_process (register Lisp_Object proc)
656 register Lisp_Object pair;
658 pair = Frassq (proc, Vprocess_alist);
659 Vprocess_alist = Fdelq (pair, Vprocess_alist);
661 deactivate_process (proc);
665 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
666 doc: /* Return t if OBJECT is a process. */)
667 (Lisp_Object object)
669 return PROCESSP (object) ? Qt : Qnil;
672 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
673 doc: /* Return the process named NAME, or nil if there is none. */)
674 (register Lisp_Object name)
676 if (PROCESSP (name))
677 return name;
678 CHECK_STRING (name);
679 return Fcdr (Fassoc (name, Vprocess_alist));
682 /* This is how commands for the user decode process arguments. It
683 accepts a process, a process name, a buffer, a buffer name, or nil.
684 Buffers denote the first process in the buffer, and nil denotes the
685 current buffer. */
687 static Lisp_Object
688 get_process (register Lisp_Object name)
690 register Lisp_Object proc, obj;
691 if (STRINGP (name))
693 obj = Fget_process (name);
694 if (NILP (obj))
695 obj = Fget_buffer (name);
696 if (NILP (obj))
697 error ("Process %s does not exist", SDATA (name));
699 else if (NILP (name))
700 obj = Fcurrent_buffer ();
701 else
702 obj = name;
704 /* Now obj should be either a buffer object or a process object.
706 if (BUFFERP (obj))
708 proc = Fget_buffer_process (obj);
709 if (NILP (proc))
710 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
712 else
714 CHECK_PROCESS (obj);
715 proc = obj;
717 return proc;
721 #ifdef SIGCHLD
722 /* Fdelete_process promises to immediately forget about the process, but in
723 reality, Emacs needs to remember those processes until they have been
724 treated by sigchld_handler; otherwise this handler would consider the
725 process as being synchronous and say that the synchronous process is
726 dead. */
727 static Lisp_Object deleted_pid_list;
728 #endif
730 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
731 doc: /* Delete PROCESS: kill it and forget about it immediately.
732 PROCESS may be a process, a buffer, the name of a process or buffer, or
733 nil, indicating the current buffer's process. */)
734 (register Lisp_Object process)
736 register struct Lisp_Process *p;
738 process = get_process (process);
739 p = XPROCESS (process);
741 p->raw_status_new = 0;
742 if (NETCONN1_P (p) || SERIALCONN1_P (p))
744 p->status = Fcons (Qexit, Fcons (make_number (0), Qnil));
745 p->tick = ++process_tick;
746 status_notify (p);
747 redisplay_preserve_echo_area (13);
749 else if (p->infd >= 0)
751 #ifdef SIGCHLD
752 Lisp_Object symbol;
753 /* Assignment to EMACS_INT stops GCC whining about limited range
754 of data type. */
755 EMACS_INT pid = p->pid;
757 /* No problem storing the pid here, as it is still in Vprocess_alist. */
758 deleted_pid_list = Fcons (make_fixnum_or_float (pid),
759 /* GC treated elements set to nil. */
760 Fdelq (Qnil, deleted_pid_list));
761 /* If the process has already signaled, remove it from the list. */
762 if (p->raw_status_new)
763 update_status (p);
764 symbol = p->status;
765 if (CONSP (p->status))
766 symbol = XCAR (p->status);
767 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit))
768 deleted_pid_list
769 = Fdelete (make_fixnum_or_float (pid), deleted_pid_list);
770 else
771 #endif
773 Fkill_process (process, Qnil);
774 /* Do this now, since remove_process will make sigchld_handler do nothing. */
775 p->status
776 = Fcons (Qsignal, Fcons (make_number (SIGKILL), Qnil));
777 p->tick = ++process_tick;
778 status_notify (p);
779 redisplay_preserve_echo_area (13);
782 remove_process (process);
783 return Qnil;
786 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
787 doc: /* Return the status of PROCESS.
788 The returned value is one of the following symbols:
789 run -- for a process that is running.
790 stop -- for a process stopped but continuable.
791 exit -- for a process that has exited.
792 signal -- for a process that has got a fatal signal.
793 open -- for a network stream connection that is open.
794 listen -- for a network stream server that is listening.
795 closed -- for a network stream connection that is closed.
796 connect -- when waiting for a non-blocking connection to complete.
797 failed -- when a non-blocking connection has failed.
798 nil -- if arg is a process name and no such process exists.
799 PROCESS may be a process, a buffer, the name of a process, or
800 nil, indicating the current buffer's process. */)
801 (register Lisp_Object process)
803 register struct Lisp_Process *p;
804 register Lisp_Object status;
806 if (STRINGP (process))
807 process = Fget_process (process);
808 else
809 process = get_process (process);
811 if (NILP (process))
812 return process;
814 p = XPROCESS (process);
815 if (p->raw_status_new)
816 update_status (p);
817 status = p->status;
818 if (CONSP (status))
819 status = XCAR (status);
820 if (NETCONN1_P (p) || SERIALCONN1_P (p))
822 if (EQ (status, Qexit))
823 status = Qclosed;
824 else if (EQ (p->command, Qt))
825 status = Qstop;
826 else if (EQ (status, Qrun))
827 status = Qopen;
829 return status;
832 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
833 1, 1, 0,
834 doc: /* Return the exit status of PROCESS or the signal number that killed it.
835 If PROCESS has not yet exited or died, return 0. */)
836 (register Lisp_Object process)
838 CHECK_PROCESS (process);
839 if (XPROCESS (process)->raw_status_new)
840 update_status (XPROCESS (process));
841 if (CONSP (XPROCESS (process)->status))
842 return XCAR (XCDR (XPROCESS (process)->status));
843 return make_number (0);
846 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
847 doc: /* Return the process id of PROCESS.
848 This is the pid of the external process which PROCESS uses or talks to.
849 For a network connection, this value is nil. */)
850 (register Lisp_Object process)
852 /* Assignment to EMACS_INT stops GCC whining about limited range of
853 data type. */
854 EMACS_INT pid;
856 CHECK_PROCESS (process);
857 pid = XPROCESS (process)->pid;
858 return (pid ? make_fixnum_or_float (pid) : Qnil);
861 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
862 doc: /* Return the name of PROCESS, as a string.
863 This is the name of the program invoked in PROCESS,
864 possibly modified to make it unique among process names. */)
865 (register Lisp_Object process)
867 CHECK_PROCESS (process);
868 return XPROCESS (process)->name;
871 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
872 doc: /* Return the command that was executed to start PROCESS.
873 This is a list of strings, the first string being the program executed
874 and the rest of the strings being the arguments given to it.
875 For a network or serial process, this is nil (process is running) or t
876 \(process is stopped). */)
877 (register Lisp_Object process)
879 CHECK_PROCESS (process);
880 return XPROCESS (process)->command;
883 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
884 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
885 This is the terminal that the process itself reads and writes on,
886 not the name of the pty that Emacs uses to talk with that terminal. */)
887 (register Lisp_Object process)
889 CHECK_PROCESS (process);
890 return XPROCESS (process)->tty_name;
893 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
894 2, 2, 0,
895 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil). */)
896 (register Lisp_Object process, Lisp_Object buffer)
898 struct Lisp_Process *p;
900 CHECK_PROCESS (process);
901 if (!NILP (buffer))
902 CHECK_BUFFER (buffer);
903 p = XPROCESS (process);
904 p->buffer = buffer;
905 if (NETCONN1_P (p) || SERIALCONN1_P (p))
906 p->childp = Fplist_put (p->childp, QCbuffer, buffer);
907 setup_process_coding_systems (process);
908 return buffer;
911 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
912 1, 1, 0,
913 doc: /* Return the buffer PROCESS is associated with.
914 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
915 (register Lisp_Object process)
917 CHECK_PROCESS (process);
918 return XPROCESS (process)->buffer;
921 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
922 1, 1, 0,
923 doc: /* Return the marker for the end of the last output from PROCESS. */)
924 (register Lisp_Object process)
926 CHECK_PROCESS (process);
927 return XPROCESS (process)->mark;
930 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
931 2, 2, 0,
932 doc: /* Give PROCESS the filter function FILTER; nil means no filter.
933 A value of t means stop accepting output from the process.
935 When a process has a filter, its buffer is not used for output.
936 Instead, each time it does output, the entire string of output is
937 passed to the filter.
939 The filter gets two arguments: the process and the string of output.
940 The string argument is normally a multibyte string, except:
941 - if the process' input coding system is no-conversion or raw-text,
942 it is a unibyte string (the non-converted input), or else
943 - if `default-enable-multibyte-characters' is nil, it is a unibyte
944 string (the result of converting the decoded input multibyte
945 string to unibyte with `string-make-unibyte'). */)
946 (register Lisp_Object process, Lisp_Object filter)
948 struct Lisp_Process *p;
950 CHECK_PROCESS (process);
951 p = XPROCESS (process);
953 /* Don't signal an error if the process' input file descriptor
954 is closed. This could make debugging Lisp more difficult,
955 for example when doing something like
957 (setq process (start-process ...))
958 (debug)
959 (set-process-filter process ...) */
961 if (p->infd >= 0)
963 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
965 FD_CLR (p->infd, &input_wait_mask);
966 FD_CLR (p->infd, &non_keyboard_wait_mask);
968 else if (EQ (p->filter, Qt)
969 /* Network or serial process not stopped: */
970 && !EQ (p->command, Qt))
972 FD_SET (p->infd, &input_wait_mask);
973 FD_SET (p->infd, &non_keyboard_wait_mask);
977 p->filter = filter;
978 if (NETCONN1_P (p) || SERIALCONN1_P (p))
979 p->childp = Fplist_put (p->childp, QCfilter, filter);
980 setup_process_coding_systems (process);
981 return filter;
984 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
985 1, 1, 0,
986 doc: /* Returns the filter function of PROCESS; nil if none.
987 See `set-process-filter' for more info on filter functions. */)
988 (register Lisp_Object process)
990 CHECK_PROCESS (process);
991 return XPROCESS (process)->filter;
994 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
995 2, 2, 0,
996 doc: /* Give PROCESS the sentinel SENTINEL; nil for none.
997 The sentinel is called as a function when the process changes state.
998 It gets two arguments: the process, and a string describing the change. */)
999 (register Lisp_Object process, Lisp_Object sentinel)
1001 struct Lisp_Process *p;
1003 CHECK_PROCESS (process);
1004 p = XPROCESS (process);
1006 p->sentinel = sentinel;
1007 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1008 p->childp = Fplist_put (p->childp, QCsentinel, sentinel);
1009 return sentinel;
1012 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1013 1, 1, 0,
1014 doc: /* Return the sentinel of PROCESS; nil if none.
1015 See `set-process-sentinel' for more info on sentinels. */)
1016 (register Lisp_Object process)
1018 CHECK_PROCESS (process);
1019 return XPROCESS (process)->sentinel;
1022 DEFUN ("set-process-window-size", Fset_process_window_size,
1023 Sset_process_window_size, 3, 3, 0,
1024 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1025 (register Lisp_Object process, Lisp_Object height, Lisp_Object width)
1027 CHECK_PROCESS (process);
1028 CHECK_NATNUM (height);
1029 CHECK_NATNUM (width);
1031 if (XPROCESS (process)->infd < 0
1032 || set_window_size (XPROCESS (process)->infd,
1033 XINT (height), XINT (width)) <= 0)
1034 return Qnil;
1035 else
1036 return Qt;
1039 DEFUN ("set-process-inherit-coding-system-flag",
1040 Fset_process_inherit_coding_system_flag,
1041 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1042 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1043 If the second argument FLAG is non-nil, then the variable
1044 `buffer-file-coding-system' of the buffer associated with PROCESS
1045 will be bound to the value of the coding system used to decode
1046 the process output.
1048 This is useful when the coding system specified for the process buffer
1049 leaves either the character code conversion or the end-of-line conversion
1050 unspecified, or if the coding system used to decode the process output
1051 is more appropriate for saving the process buffer.
1053 Binding the variable `inherit-process-coding-system' to non-nil before
1054 starting the process is an alternative way of setting the inherit flag
1055 for the process which will run. */)
1056 (register Lisp_Object process, Lisp_Object flag)
1058 CHECK_PROCESS (process);
1059 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1060 return flag;
1063 DEFUN ("set-process-query-on-exit-flag",
1064 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1065 2, 2, 0,
1066 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1067 If the second argument FLAG is non-nil, Emacs will query the user before
1068 exiting or killing a buffer if PROCESS is running. */)
1069 (register Lisp_Object process, Lisp_Object flag)
1071 CHECK_PROCESS (process);
1072 XPROCESS (process)->kill_without_query = NILP (flag);
1073 return flag;
1076 DEFUN ("process-query-on-exit-flag",
1077 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1078 1, 1, 0,
1079 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1080 (register Lisp_Object process)
1082 CHECK_PROCESS (process);
1083 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1086 #ifdef DATAGRAM_SOCKETS
1087 static Lisp_Object Fprocess_datagram_address (Lisp_Object);
1088 #endif
1090 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1091 1, 2, 0,
1092 doc: /* Return the contact info of PROCESS; t for a real child.
1093 For a network or serial connection, the value depends on the optional
1094 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1095 SERVICE) for a network connection or (PORT SPEED) for a serial
1096 connection. If KEY is t, the complete contact information for the
1097 connection is returned, else the specific value for the keyword KEY is
1098 returned. See `make-network-process' or `make-serial-process' for a
1099 list of keywords. */)
1100 (register Lisp_Object process, Lisp_Object key)
1102 Lisp_Object contact;
1104 CHECK_PROCESS (process);
1105 contact = XPROCESS (process)->childp;
1107 #ifdef DATAGRAM_SOCKETS
1108 if (DATAGRAM_CONN_P (process)
1109 && (EQ (key, Qt) || EQ (key, QCremote)))
1110 contact = Fplist_put (contact, QCremote,
1111 Fprocess_datagram_address (process));
1112 #endif
1114 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1115 return contact;
1116 if (NILP (key) && NETCONN_P (process))
1117 return Fcons (Fplist_get (contact, QChost),
1118 Fcons (Fplist_get (contact, QCservice), Qnil));
1119 if (NILP (key) && SERIALCONN_P (process))
1120 return Fcons (Fplist_get (contact, QCport),
1121 Fcons (Fplist_get (contact, QCspeed), Qnil));
1122 return Fplist_get (contact, key);
1125 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1126 1, 1, 0,
1127 doc: /* Return the plist of PROCESS. */)
1128 (register Lisp_Object process)
1130 CHECK_PROCESS (process);
1131 return XPROCESS (process)->plist;
1134 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1135 2, 2, 0,
1136 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1137 (register Lisp_Object process, Lisp_Object plist)
1139 CHECK_PROCESS (process);
1140 CHECK_LIST (plist);
1142 XPROCESS (process)->plist = plist;
1143 return plist;
1146 #if 0 /* Turned off because we don't currently record this info
1147 in the process. Perhaps add it. */
1148 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1149 doc: /* Return the connection type of PROCESS.
1150 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1151 a socket connection. */)
1152 (Lisp_Object process)
1154 return XPROCESS (process)->type;
1156 #endif
1158 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1159 doc: /* Return the connection type of PROCESS.
1160 The value is either the symbol `real', `network', or `serial'.
1161 PROCESS may be a process, a buffer, the name of a process or buffer, or
1162 nil, indicating the current buffer's process. */)
1163 (Lisp_Object process)
1165 Lisp_Object proc;
1166 proc = get_process (process);
1167 return XPROCESS (proc)->type;
1170 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1171 1, 2, 0,
1172 doc: /* Convert network ADDRESS from internal format to a string.
1173 A 4 or 5 element vector represents an IPv4 address (with port number).
1174 An 8 or 9 element vector represents an IPv6 address (with port number).
1175 If optional second argument OMIT-PORT is non-nil, don't include a port
1176 number in the string, even when present in ADDRESS.
1177 Returns nil if format of ADDRESS is invalid. */)
1178 (Lisp_Object address, Lisp_Object omit_port)
1180 if (NILP (address))
1181 return Qnil;
1183 if (STRINGP (address)) /* AF_LOCAL */
1184 return address;
1186 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1188 register struct Lisp_Vector *p = XVECTOR (address);
1189 EMACS_UINT size = p->header.size;
1190 Lisp_Object args[10];
1191 int nargs, i;
1193 if (size == 4 || (size == 5 && !NILP (omit_port)))
1195 args[0] = build_string ("%d.%d.%d.%d");
1196 nargs = 4;
1198 else if (size == 5)
1200 args[0] = build_string ("%d.%d.%d.%d:%d");
1201 nargs = 5;
1203 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1205 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1206 nargs = 8;
1208 else if (size == 9)
1210 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1211 nargs = 9;
1213 else
1214 return Qnil;
1216 for (i = 0; i < nargs; i++)
1218 EMACS_INT element = XINT (p->contents[i]);
1220 if (element < 0 || element > 65535)
1221 return Qnil;
1223 if (nargs <= 5 /* IPv4 */
1224 && i < 4 /* host, not port */
1225 && element > 255)
1226 return Qnil;
1228 args[i+1] = p->contents[i];
1231 return Fformat (nargs+1, args);
1234 if (CONSP (address))
1236 Lisp_Object args[2];
1237 args[0] = build_string ("<Family %d>");
1238 args[1] = Fcar (address);
1239 return Fformat (2, args);
1242 return Qnil;
1245 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1246 doc: /* Return a list of all processes. */)
1247 (void)
1249 return Fmapcar (Qcdr, Vprocess_alist);
1252 /* Starting asynchronous inferior processes. */
1254 static Lisp_Object start_process_unwind (Lisp_Object proc);
1256 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1257 doc: /* Start a program in a subprocess. Return the process object for it.
1258 NAME is name for process. It is modified if necessary to make it unique.
1259 BUFFER is the buffer (or buffer name) to associate with the process.
1261 Process output (both standard output and standard error streams) goes
1262 at end of BUFFER, unless you specify an output stream or filter
1263 function to handle the output. BUFFER may also be nil, meaning that
1264 this process is not associated with any buffer.
1266 PROGRAM is the program file name. It is searched for in `exec-path'
1267 (which see). If nil, just associate a pty with the buffer. Remaining
1268 arguments are strings to give program as arguments.
1270 If you want to separate standard output from standard error, invoke
1271 the command through a shell and redirect one of them using the shell
1272 syntax.
1274 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1275 (size_t nargs, register Lisp_Object *args)
1277 Lisp_Object buffer, name, program, proc, current_dir, tem;
1278 register unsigned char **new_argv;
1279 register size_t i;
1280 int count = SPECPDL_INDEX ();
1282 buffer = args[1];
1283 if (!NILP (buffer))
1284 buffer = Fget_buffer_create (buffer);
1286 /* Make sure that the child will be able to chdir to the current
1287 buffer's current directory, or its unhandled equivalent. We
1288 can't just have the child check for an error when it does the
1289 chdir, since it's in a vfork.
1291 We have to GCPRO around this because Fexpand_file_name and
1292 Funhandled_file_name_directory might call a file name handling
1293 function. The argument list is protected by the caller, so all
1294 we really have to worry about is buffer. */
1296 struct gcpro gcpro1, gcpro2;
1298 current_dir = BVAR (current_buffer, directory);
1300 GCPRO2 (buffer, current_dir);
1302 current_dir = Funhandled_file_name_directory (current_dir);
1303 if (NILP (current_dir))
1304 /* If the file name handler says that current_dir is unreachable, use
1305 a sensible default. */
1306 current_dir = build_string ("~/");
1307 current_dir = expand_and_dir_to_file (current_dir, Qnil);
1308 if (NILP (Ffile_accessible_directory_p (current_dir)))
1309 report_file_error ("Setting current directory",
1310 Fcons (BVAR (current_buffer, directory), Qnil));
1312 UNGCPRO;
1315 name = args[0];
1316 CHECK_STRING (name);
1318 program = args[2];
1320 if (!NILP (program))
1321 CHECK_STRING (program);
1323 proc = make_process (name);
1324 /* If an error occurs and we can't start the process, we want to
1325 remove it from the process list. This means that each error
1326 check in create_process doesn't need to call remove_process
1327 itself; it's all taken care of here. */
1328 record_unwind_protect (start_process_unwind, proc);
1330 XPROCESS (proc)->childp = Qt;
1331 XPROCESS (proc)->plist = Qnil;
1332 XPROCESS (proc)->type = Qreal;
1333 XPROCESS (proc)->buffer = buffer;
1334 XPROCESS (proc)->sentinel = Qnil;
1335 XPROCESS (proc)->filter = Qnil;
1336 XPROCESS (proc)->command = Flist (nargs - 2, args + 2);
1338 #ifdef HAVE_GNUTLS
1339 /* AKA GNUTLS_INITSTAGE(proc). */
1340 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1341 XPROCESS (proc)->gnutls_cred_type = Qnil;
1342 #endif
1344 #ifdef ADAPTIVE_READ_BUFFERING
1345 XPROCESS (proc)->adaptive_read_buffering
1346 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1347 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1348 #endif
1350 /* Make the process marker point into the process buffer (if any). */
1351 if (BUFFERP (buffer))
1352 set_marker_both (XPROCESS (proc)->mark, buffer,
1353 BUF_ZV (XBUFFER (buffer)),
1354 BUF_ZV_BYTE (XBUFFER (buffer)));
1357 /* Decide coding systems for communicating with the process. Here
1358 we don't setup the structure coding_system nor pay attention to
1359 unibyte mode. They are done in create_process. */
1361 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1362 Lisp_Object coding_systems = Qt;
1363 Lisp_Object val, *args2;
1364 struct gcpro gcpro1, gcpro2;
1366 val = Vcoding_system_for_read;
1367 if (NILP (val))
1369 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
1370 args2[0] = Qstart_process;
1371 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1372 GCPRO2 (proc, current_dir);
1373 if (!NILP (program))
1374 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1375 UNGCPRO;
1376 if (CONSP (coding_systems))
1377 val = XCAR (coding_systems);
1378 else if (CONSP (Vdefault_process_coding_system))
1379 val = XCAR (Vdefault_process_coding_system);
1381 XPROCESS (proc)->decode_coding_system = val;
1383 val = Vcoding_system_for_write;
1384 if (NILP (val))
1386 if (EQ (coding_systems, Qt))
1388 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
1389 args2[0] = Qstart_process;
1390 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1391 GCPRO2 (proc, current_dir);
1392 if (!NILP (program))
1393 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1394 UNGCPRO;
1396 if (CONSP (coding_systems))
1397 val = XCDR (coding_systems);
1398 else if (CONSP (Vdefault_process_coding_system))
1399 val = XCDR (Vdefault_process_coding_system);
1401 XPROCESS (proc)->encode_coding_system = val;
1402 /* Note: At this momemnt, the above coding system may leave
1403 text-conversion or eol-conversion unspecified. They will be
1404 decided after we read output from the process and decode it by
1405 some coding system, or just before we actually send a text to
1406 the process. */
1410 XPROCESS (proc)->decoding_buf = empty_unibyte_string;
1411 XPROCESS (proc)->decoding_carryover = 0;
1412 XPROCESS (proc)->encoding_buf = empty_unibyte_string;
1414 XPROCESS (proc)->inherit_coding_system_flag
1415 = !(NILP (buffer) || !inherit_process_coding_system);
1417 if (!NILP (program))
1419 /* If program file name is not absolute, search our path for it.
1420 Put the name we will really use in TEM. */
1421 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1422 && !(SCHARS (program) > 1
1423 && IS_DEVICE_SEP (SREF (program, 1))))
1425 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1427 tem = Qnil;
1428 GCPRO4 (name, program, buffer, current_dir);
1429 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1430 UNGCPRO;
1431 if (NILP (tem))
1432 report_file_error ("Searching for program", Fcons (program, Qnil));
1433 tem = Fexpand_file_name (tem, Qnil);
1435 else
1437 if (!NILP (Ffile_directory_p (program)))
1438 error ("Specified program for new process is a directory");
1439 tem = program;
1442 /* If program file name starts with /: for quoting a magic name,
1443 discard that. */
1444 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1445 && SREF (tem, 1) == ':')
1446 tem = Fsubstring (tem, make_number (2), Qnil);
1449 Lisp_Object arg_encoding = Qnil;
1450 struct gcpro gcpro1;
1451 GCPRO1 (tem);
1453 /* Encode the file name and put it in NEW_ARGV.
1454 That's where the child will use it to execute the program. */
1455 tem = Fcons (ENCODE_FILE (tem), Qnil);
1457 /* Here we encode arguments by the coding system used for sending
1458 data to the process. We don't support using different coding
1459 systems for encoding arguments and for encoding data sent to the
1460 process. */
1462 for (i = 3; i < nargs; i++)
1464 tem = Fcons (args[i], tem);
1465 CHECK_STRING (XCAR (tem));
1466 if (STRING_MULTIBYTE (XCAR (tem)))
1468 if (NILP (arg_encoding))
1469 arg_encoding = (complement_process_encoding_system
1470 (XPROCESS (proc)->encode_coding_system));
1471 XSETCAR (tem,
1472 code_convert_string_norecord
1473 (XCAR (tem), arg_encoding, 1));
1477 UNGCPRO;
1480 /* Now that everything is encoded we can collect the strings into
1481 NEW_ARGV. */
1482 new_argv = (unsigned char **) alloca ((nargs - 1) * sizeof (char *));
1483 new_argv[nargs - 2] = 0;
1485 for (i = nargs - 2; i-- != 0; )
1487 new_argv[i] = SDATA (XCAR (tem));
1488 tem = XCDR (tem);
1491 create_process (proc, (char **) new_argv, current_dir);
1493 else
1494 create_pty (proc);
1496 return unbind_to (count, proc);
1499 /* This function is the unwind_protect form for Fstart_process. If
1500 PROC doesn't have its pid set, then we know someone has signaled
1501 an error and the process wasn't started successfully, so we should
1502 remove it from the process list. */
1503 static Lisp_Object
1504 start_process_unwind (Lisp_Object proc)
1506 if (!PROCESSP (proc))
1507 abort ();
1509 /* Was PROC started successfully? */
1510 if (XPROCESS (proc)->pid == -1)
1511 remove_process (proc);
1513 return Qnil;
1516 static void
1517 create_process_1 (struct atimer *timer)
1519 /* Nothing to do. */
1523 static void
1524 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1526 int inchannel, outchannel;
1527 pid_t pid;
1528 int sv[2];
1529 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1530 int wait_child_setup[2];
1531 #endif
1532 sigset_t procmask;
1533 sigset_t blocked;
1534 struct sigaction sigint_action;
1535 struct sigaction sigquit_action;
1536 struct sigaction sigpipe_action;
1537 #ifdef AIX
1538 struct sigaction sighup_action;
1539 #endif
1540 /* Use volatile to protect variables from being clobbered by longjmp. */
1541 volatile int forkin, forkout;
1542 volatile int pty_flag = 0;
1543 #ifndef USE_CRT_DLL
1544 extern char **environ;
1545 #endif
1547 inchannel = outchannel = -1;
1549 #ifdef HAVE_PTYS
1550 if (!NILP (Vprocess_connection_type))
1551 outchannel = inchannel = allocate_pty ();
1553 if (inchannel >= 0)
1555 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1556 /* On most USG systems it does not work to open the pty's tty here,
1557 then close it and reopen it in the child. */
1558 #ifdef O_NOCTTY
1559 /* Don't let this terminal become our controlling terminal
1560 (in case we don't have one). */
1561 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1562 #else
1563 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
1564 #endif
1565 if (forkin < 0)
1566 report_file_error ("Opening pty", Qnil);
1567 #else
1568 forkin = forkout = -1;
1569 #endif /* not USG, or USG_SUBTTY_WORKS */
1570 pty_flag = 1;
1572 else
1573 #endif /* HAVE_PTYS */
1575 int tem;
1576 tem = pipe (sv);
1577 if (tem < 0)
1578 report_file_error ("Creating pipe", Qnil);
1579 inchannel = sv[0];
1580 forkout = sv[1];
1581 tem = pipe (sv);
1582 if (tem < 0)
1584 emacs_close (inchannel);
1585 emacs_close (forkout);
1586 report_file_error ("Creating pipe", Qnil);
1588 outchannel = sv[1];
1589 forkin = sv[0];
1592 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1594 int tem;
1596 tem = pipe (wait_child_setup);
1597 if (tem < 0)
1598 report_file_error ("Creating pipe", Qnil);
1599 tem = fcntl (wait_child_setup[1], F_GETFD, 0);
1600 if (tem >= 0)
1601 tem = fcntl (wait_child_setup[1], F_SETFD, tem | FD_CLOEXEC);
1602 if (tem < 0)
1604 emacs_close (wait_child_setup[0]);
1605 emacs_close (wait_child_setup[1]);
1606 report_file_error ("Setting file descriptor flags", Qnil);
1609 #endif
1611 #ifdef O_NONBLOCK
1612 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1613 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1614 #else
1615 #ifdef O_NDELAY
1616 fcntl (inchannel, F_SETFL, O_NDELAY);
1617 fcntl (outchannel, F_SETFL, O_NDELAY);
1618 #endif
1619 #endif
1621 /* Record this as an active process, with its channels.
1622 As a result, child_setup will close Emacs's side of the pipes. */
1623 chan_process[inchannel] = process;
1624 XPROCESS (process)->infd = inchannel;
1625 XPROCESS (process)->outfd = outchannel;
1627 /* Previously we recorded the tty descriptor used in the subprocess.
1628 It was only used for getting the foreground tty process, so now
1629 we just reopen the device (see emacs_get_tty_pgrp) as this is
1630 more portable (see USG_SUBTTY_WORKS above). */
1632 XPROCESS (process)->pty_flag = pty_flag;
1633 XPROCESS (process)->status = Qrun;
1634 setup_process_coding_systems (process);
1636 /* Delay interrupts until we have a chance to store
1637 the new fork's pid in its process structure */
1638 sigemptyset (&blocked);
1639 #ifdef SIGCHLD
1640 sigaddset (&blocked, SIGCHLD);
1641 #endif
1642 #ifdef HAVE_WORKING_VFORK
1643 /* On many hosts (e.g. Solaris 2.4), if a vforked child calls `signal',
1644 this sets the parent's signal handlers as well as the child's.
1645 So delay all interrupts whose handlers the child might munge,
1646 and record the current handlers so they can be restored later. */
1647 sigaddset (&blocked, SIGINT ); sigaction (SIGINT , 0, &sigint_action );
1648 sigaddset (&blocked, SIGQUIT); sigaction (SIGQUIT, 0, &sigquit_action);
1649 sigaddset (&blocked, SIGPIPE); sigaction (SIGPIPE, 0, &sigpipe_action);
1650 #ifdef AIX
1651 sigaddset (&blocked, SIGHUP ); sigaction (SIGHUP , 0, &sighup_action );
1652 #endif
1653 #endif /* HAVE_WORKING_VFORK */
1654 sigprocmask (SIG_BLOCK, &blocked, &procmask);
1656 FD_SET (inchannel, &input_wait_mask);
1657 FD_SET (inchannel, &non_keyboard_wait_mask);
1658 if (inchannel > max_process_desc)
1659 max_process_desc = inchannel;
1661 /* Until we store the proper pid, enable sigchld_handler
1662 to recognize an unknown pid as standing for this process.
1663 It is very important not to let this `marker' value stay
1664 in the table after this function has returned; if it does
1665 it might cause call-process to hang and subsequent asynchronous
1666 processes to get their return values scrambled. */
1667 XPROCESS (process)->pid = -1;
1669 BLOCK_INPUT;
1672 /* child_setup must clobber environ on systems with true vfork.
1673 Protect it from permanent change. */
1674 char **save_environ = environ;
1675 volatile Lisp_Object encoded_current_dir = ENCODE_FILE (current_dir);
1677 #ifndef WINDOWSNT
1678 pid = vfork ();
1679 if (pid == 0)
1680 #endif /* not WINDOWSNT */
1682 int xforkin = forkin;
1683 int xforkout = forkout;
1685 #if 0 /* This was probably a mistake--it duplicates code later on,
1686 but fails to handle all the cases. */
1687 /* Make sure SIGCHLD is not blocked in the child. */
1688 sigsetmask (SIGEMPTYMASK);
1689 #endif
1691 /* Make the pty be the controlling terminal of the process. */
1692 #ifdef HAVE_PTYS
1693 /* First, disconnect its current controlling terminal. */
1694 #ifdef HAVE_SETSID
1695 /* We tried doing setsid only if pty_flag, but it caused
1696 process_set_signal to fail on SGI when using a pipe. */
1697 setsid ();
1698 /* Make the pty's terminal the controlling terminal. */
1699 if (pty_flag && xforkin >= 0)
1701 #ifdef TIOCSCTTY
1702 /* We ignore the return value
1703 because faith@cs.unc.edu says that is necessary on Linux. */
1704 ioctl (xforkin, TIOCSCTTY, 0);
1705 #endif
1707 #else /* not HAVE_SETSID */
1708 #ifdef USG
1709 /* It's very important to call setpgrp here and no time
1710 afterwards. Otherwise, we lose our controlling tty which
1711 is set when we open the pty. */
1712 setpgrp ();
1713 #endif /* USG */
1714 #endif /* not HAVE_SETSID */
1715 #if defined (LDISC1)
1716 if (pty_flag && xforkin >= 0)
1718 struct termios t;
1719 tcgetattr (xforkin, &t);
1720 t.c_lflag = LDISC1;
1721 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1722 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
1724 #else
1725 #if defined (NTTYDISC) && defined (TIOCSETD)
1726 if (pty_flag && xforkin >= 0)
1728 /* Use new line discipline. */
1729 int ldisc = NTTYDISC;
1730 ioctl (xforkin, TIOCSETD, &ldisc);
1732 #endif
1733 #endif
1734 #ifdef TIOCNOTTY
1735 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1736 can do TIOCSPGRP only to the process's controlling tty. */
1737 if (pty_flag)
1739 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1740 I can't test it since I don't have 4.3. */
1741 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1742 if (j >= 0)
1744 ioctl (j, TIOCNOTTY, 0);
1745 emacs_close (j);
1747 #ifndef USG
1748 /* In order to get a controlling terminal on some versions
1749 of BSD, it is necessary to put the process in pgrp 0
1750 before it opens the terminal. */
1751 #ifdef HAVE_SETPGID
1752 setpgid (0, 0);
1753 #else
1754 setpgrp (0, 0);
1755 #endif
1756 #endif
1758 #endif /* TIOCNOTTY */
1760 #if !defined (DONT_REOPEN_PTY)
1761 /*** There is a suggestion that this ought to be a
1762 conditional on TIOCSPGRP,
1763 or !(defined (HAVE_SETSID) && defined (TIOCSCTTY)).
1764 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1765 that system does seem to need this code, even though
1766 both HAVE_SETSID and TIOCSCTTY are defined. */
1767 /* Now close the pty (if we had it open) and reopen it.
1768 This makes the pty the controlling terminal of the subprocess. */
1769 if (pty_flag)
1772 /* I wonder if emacs_close (emacs_open (pty_name, ...))
1773 would work? */
1774 if (xforkin >= 0)
1775 emacs_close (xforkin);
1776 xforkout = xforkin = emacs_open (pty_name, O_RDWR, 0);
1778 if (xforkin < 0)
1780 emacs_write (1, "Couldn't open the pty terminal ", 31);
1781 emacs_write (1, pty_name, strlen (pty_name));
1782 emacs_write (1, "\n", 1);
1783 _exit (1);
1787 #endif /* not DONT_REOPEN_PTY */
1789 #ifdef SETUP_SLAVE_PTY
1790 if (pty_flag)
1792 SETUP_SLAVE_PTY;
1794 #endif /* SETUP_SLAVE_PTY */
1795 #ifdef AIX
1796 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
1797 Now reenable it in the child, so it will die when we want it to. */
1798 if (pty_flag)
1799 signal (SIGHUP, SIG_DFL);
1800 #endif
1801 #endif /* HAVE_PTYS */
1803 signal (SIGINT, SIG_DFL);
1804 signal (SIGQUIT, SIG_DFL);
1805 /* GConf causes us to ignore SIGPIPE, make sure it is restored
1806 in the child. */
1807 signal (SIGPIPE, SIG_DFL);
1809 /* Stop blocking signals in the child. */
1810 sigprocmask (SIG_SETMASK, &procmask, 0);
1812 if (pty_flag)
1813 child_setup_tty (xforkout);
1814 #ifdef WINDOWSNT
1815 pid = child_setup (xforkin, xforkout, xforkout,
1816 new_argv, 1, encoded_current_dir);
1817 #else /* not WINDOWSNT */
1818 #ifdef FD_CLOEXEC
1819 emacs_close (wait_child_setup[0]);
1820 #endif
1821 child_setup (xforkin, xforkout, xforkout,
1822 new_argv, 1, encoded_current_dir);
1823 #endif /* not WINDOWSNT */
1825 environ = save_environ;
1828 UNBLOCK_INPUT;
1830 /* This runs in the Emacs process. */
1831 if (pid < 0)
1833 if (forkin >= 0)
1834 emacs_close (forkin);
1835 if (forkin != forkout && forkout >= 0)
1836 emacs_close (forkout);
1838 else
1840 /* vfork succeeded. */
1841 XPROCESS (process)->pid = pid;
1843 #ifdef WINDOWSNT
1844 register_child (pid, inchannel);
1845 #endif /* WINDOWSNT */
1847 /* If the subfork execv fails, and it exits,
1848 this close hangs. I don't know why.
1849 So have an interrupt jar it loose. */
1851 struct atimer *timer;
1852 EMACS_TIME offset;
1854 stop_polling ();
1855 EMACS_SET_SECS_USECS (offset, 1, 0);
1856 timer = start_atimer (ATIMER_RELATIVE, offset, create_process_1, 0);
1858 if (forkin >= 0)
1859 emacs_close (forkin);
1861 cancel_atimer (timer);
1862 start_polling ();
1865 if (forkin != forkout && forkout >= 0)
1866 emacs_close (forkout);
1868 #ifdef HAVE_PTYS
1869 if (pty_flag)
1870 XPROCESS (process)->tty_name = build_string (pty_name);
1871 else
1872 #endif
1873 XPROCESS (process)->tty_name = Qnil;
1875 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1876 /* Wait for child_setup to complete in case that vfork is
1877 actually defined as fork. The descriptor wait_child_setup[1]
1878 of a pipe is closed at the child side either by close-on-exec
1879 on successful execvp or the _exit call in child_setup. */
1881 char dummy;
1883 emacs_close (wait_child_setup[1]);
1884 emacs_read (wait_child_setup[0], &dummy, 1);
1885 emacs_close (wait_child_setup[0]);
1887 #endif
1890 /* Restore the signal state whether vfork succeeded or not.
1891 (We will signal an error, below, if it failed.) */
1892 #ifdef HAVE_WORKING_VFORK
1893 /* Restore the parent's signal handlers. */
1894 sigaction (SIGINT, &sigint_action, 0);
1895 sigaction (SIGQUIT, &sigquit_action, 0);
1896 sigaction (SIGPIPE, &sigpipe_action, 0);
1897 #ifdef AIX
1898 sigaction (SIGHUP, &sighup_action, 0);
1899 #endif
1900 #endif /* HAVE_WORKING_VFORK */
1901 /* Stop blocking signals in the parent. */
1902 sigprocmask (SIG_SETMASK, &procmask, 0);
1904 /* Now generate the error if vfork failed. */
1905 if (pid < 0)
1906 report_file_error ("Doing vfork", Qnil);
1909 void
1910 create_pty (Lisp_Object process)
1912 int inchannel, outchannel;
1913 int pty_flag = 0;
1915 inchannel = outchannel = -1;
1917 #ifdef HAVE_PTYS
1918 if (!NILP (Vprocess_connection_type))
1919 outchannel = inchannel = allocate_pty ();
1921 if (inchannel >= 0)
1923 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1924 /* On most USG systems it does not work to open the pty's tty here,
1925 then close it and reopen it in the child. */
1926 #ifdef O_NOCTTY
1927 /* Don't let this terminal become our controlling terminal
1928 (in case we don't have one). */
1929 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1930 #else
1931 int forkout = emacs_open (pty_name, O_RDWR, 0);
1932 #endif
1933 if (forkout < 0)
1934 report_file_error ("Opening pty", Qnil);
1935 #if defined (DONT_REOPEN_PTY)
1936 /* In the case that vfork is defined as fork, the parent process
1937 (Emacs) may send some data before the child process completes
1938 tty options setup. So we setup tty before forking. */
1939 child_setup_tty (forkout);
1940 #endif /* DONT_REOPEN_PTY */
1941 #endif /* not USG, or USG_SUBTTY_WORKS */
1942 pty_flag = 1;
1944 #endif /* HAVE_PTYS */
1946 #ifdef O_NONBLOCK
1947 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1948 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1949 #else
1950 #ifdef O_NDELAY
1951 fcntl (inchannel, F_SETFL, O_NDELAY);
1952 fcntl (outchannel, F_SETFL, O_NDELAY);
1953 #endif
1954 #endif
1956 /* Record this as an active process, with its channels.
1957 As a result, child_setup will close Emacs's side of the pipes. */
1958 chan_process[inchannel] = process;
1959 XPROCESS (process)->infd = inchannel;
1960 XPROCESS (process)->outfd = outchannel;
1962 /* Previously we recorded the tty descriptor used in the subprocess.
1963 It was only used for getting the foreground tty process, so now
1964 we just reopen the device (see emacs_get_tty_pgrp) as this is
1965 more portable (see USG_SUBTTY_WORKS above). */
1967 XPROCESS (process)->pty_flag = pty_flag;
1968 XPROCESS (process)->status = Qrun;
1969 setup_process_coding_systems (process);
1971 FD_SET (inchannel, &input_wait_mask);
1972 FD_SET (inchannel, &non_keyboard_wait_mask);
1973 if (inchannel > max_process_desc)
1974 max_process_desc = inchannel;
1976 XPROCESS (process)->pid = -2;
1977 #ifdef HAVE_PTYS
1978 if (pty_flag)
1979 XPROCESS (process)->tty_name = build_string (pty_name);
1980 else
1981 #endif
1982 XPROCESS (process)->tty_name = Qnil;
1986 /* Convert an internal struct sockaddr to a lisp object (vector or string).
1987 The address family of sa is not included in the result. */
1989 static Lisp_Object
1990 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
1992 Lisp_Object address;
1993 int i;
1994 unsigned char *cp;
1995 register struct Lisp_Vector *p;
1997 /* Workaround for a bug in getsockname on BSD: Names bound to
1998 sockets in the UNIX domain are inaccessible; getsockname returns
1999 a zero length name. */
2000 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2001 return empty_unibyte_string;
2003 switch (sa->sa_family)
2005 case AF_INET:
2007 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2008 len = sizeof (sin->sin_addr) + 1;
2009 address = Fmake_vector (make_number (len), Qnil);
2010 p = XVECTOR (address);
2011 p->contents[--len] = make_number (ntohs (sin->sin_port));
2012 cp = (unsigned char *) &sin->sin_addr;
2013 break;
2015 #ifdef AF_INET6
2016 case AF_INET6:
2018 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2019 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2020 len = sizeof (sin6->sin6_addr)/2 + 1;
2021 address = Fmake_vector (make_number (len), Qnil);
2022 p = XVECTOR (address);
2023 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2024 for (i = 0; i < len; i++)
2025 p->contents[i] = make_number (ntohs (ip6[i]));
2026 return address;
2028 #endif
2029 #ifdef HAVE_LOCAL_SOCKETS
2030 case AF_LOCAL:
2032 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2033 for (i = 0; i < sizeof (sockun->sun_path); i++)
2034 if (sockun->sun_path[i] == 0)
2035 break;
2036 return make_unibyte_string (sockun->sun_path, i);
2038 #endif
2039 default:
2040 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2041 address = Fcons (make_number (sa->sa_family),
2042 Fmake_vector (make_number (len), Qnil));
2043 p = XVECTOR (XCDR (address));
2044 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2045 break;
2048 i = 0;
2049 while (i < len)
2050 p->contents[i++] = make_number (*cp++);
2052 return address;
2056 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2058 static int
2059 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2061 register struct Lisp_Vector *p;
2063 if (VECTORP (address))
2065 p = XVECTOR (address);
2066 if (p->header.size == 5)
2068 *familyp = AF_INET;
2069 return sizeof (struct sockaddr_in);
2071 #ifdef AF_INET6
2072 else if (p->header.size == 9)
2074 *familyp = AF_INET6;
2075 return sizeof (struct sockaddr_in6);
2077 #endif
2079 #ifdef HAVE_LOCAL_SOCKETS
2080 else if (STRINGP (address))
2082 *familyp = AF_LOCAL;
2083 return sizeof (struct sockaddr_un);
2085 #endif
2086 else if (CONSP (address) && INTEGERP (XCAR (address)) && VECTORP (XCDR (address)))
2088 struct sockaddr *sa;
2089 *familyp = XINT (XCAR (address));
2090 p = XVECTOR (XCDR (address));
2091 return p->header.size + sizeof (sa->sa_family);
2093 return 0;
2096 /* Convert an address object (vector or string) to an internal sockaddr.
2098 The address format has been basically validated by
2099 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2100 it could have come from user data. So if FAMILY is not valid,
2101 we return after zeroing *SA. */
2103 static void
2104 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2106 register struct Lisp_Vector *p;
2107 register unsigned char *cp = NULL;
2108 register int i;
2110 memset (sa, 0, len);
2112 if (VECTORP (address))
2114 p = XVECTOR (address);
2115 if (family == AF_INET)
2117 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2118 len = sizeof (sin->sin_addr) + 1;
2119 i = XINT (p->contents[--len]);
2120 sin->sin_port = htons (i);
2121 cp = (unsigned char *)&sin->sin_addr;
2122 sa->sa_family = family;
2124 #ifdef AF_INET6
2125 else if (family == AF_INET6)
2127 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2128 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2129 len = sizeof (sin6->sin6_addr) + 1;
2130 i = XINT (p->contents[--len]);
2131 sin6->sin6_port = htons (i);
2132 for (i = 0; i < len; i++)
2133 if (INTEGERP (p->contents[i]))
2135 int j = XFASTINT (p->contents[i]) & 0xffff;
2136 ip6[i] = ntohs (j);
2138 sa->sa_family = family;
2139 return;
2141 #endif
2142 else
2143 return;
2145 else if (STRINGP (address))
2147 #ifdef HAVE_LOCAL_SOCKETS
2148 if (family == AF_LOCAL)
2150 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2151 cp = SDATA (address);
2152 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2153 sockun->sun_path[i] = *cp++;
2154 sa->sa_family = family;
2156 #endif
2157 return;
2159 else
2161 p = XVECTOR (XCDR (address));
2162 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2165 for (i = 0; i < len; i++)
2166 if (INTEGERP (p->contents[i]))
2167 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2170 #ifdef DATAGRAM_SOCKETS
2171 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2172 1, 1, 0,
2173 doc: /* Get the current datagram address associated with PROCESS. */)
2174 (Lisp_Object process)
2176 int channel;
2178 CHECK_PROCESS (process);
2180 if (!DATAGRAM_CONN_P (process))
2181 return Qnil;
2183 channel = XPROCESS (process)->infd;
2184 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2185 datagram_address[channel].len);
2188 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2189 2, 2, 0,
2190 doc: /* Set the datagram address for PROCESS to ADDRESS.
2191 Returns nil upon error setting address, ADDRESS otherwise. */)
2192 (Lisp_Object process, Lisp_Object address)
2194 int channel;
2195 int family, len;
2197 CHECK_PROCESS (process);
2199 if (!DATAGRAM_CONN_P (process))
2200 return Qnil;
2202 channel = XPROCESS (process)->infd;
2204 len = get_lisp_to_sockaddr_size (address, &family);
2205 if (datagram_address[channel].len != len)
2206 return Qnil;
2207 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2208 return address;
2210 #endif
2213 static const struct socket_options {
2214 /* The name of this option. Should be lowercase version of option
2215 name without SO_ prefix. */
2216 const char *name;
2217 /* Option level SOL_... */
2218 int optlevel;
2219 /* Option number SO_... */
2220 int optnum;
2221 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2222 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2223 } socket_options[] =
2225 #ifdef SO_BINDTODEVICE
2226 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2227 #endif
2228 #ifdef SO_BROADCAST
2229 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2230 #endif
2231 #ifdef SO_DONTROUTE
2232 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2233 #endif
2234 #ifdef SO_KEEPALIVE
2235 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2236 #endif
2237 #ifdef SO_LINGER
2238 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2239 #endif
2240 #ifdef SO_OOBINLINE
2241 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2242 #endif
2243 #ifdef SO_PRIORITY
2244 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2245 #endif
2246 #ifdef SO_REUSEADDR
2247 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2248 #endif
2249 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2252 /* Set option OPT to value VAL on socket S.
2254 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2255 Signals an error if setting a known option fails.
2258 static int
2259 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2261 char *name;
2262 const struct socket_options *sopt;
2263 int ret = 0;
2265 CHECK_SYMBOL (opt);
2267 name = SSDATA (SYMBOL_NAME (opt));
2268 for (sopt = socket_options; sopt->name; sopt++)
2269 if (strcmp (name, sopt->name) == 0)
2270 break;
2272 switch (sopt->opttype)
2274 case SOPT_BOOL:
2276 int optval;
2277 optval = NILP (val) ? 0 : 1;
2278 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2279 &optval, sizeof (optval));
2280 break;
2283 case SOPT_INT:
2285 int optval;
2286 if (INTEGERP (val))
2287 optval = XINT (val);
2288 else
2289 error ("Bad option value for %s", name);
2290 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2291 &optval, sizeof (optval));
2292 break;
2295 #ifdef SO_BINDTODEVICE
2296 case SOPT_IFNAME:
2298 char devname[IFNAMSIZ+1];
2300 /* This is broken, at least in the Linux 2.4 kernel.
2301 To unbind, the arg must be a zero integer, not the empty string.
2302 This should work on all systems. KFS. 2003-09-23. */
2303 memset (devname, 0, sizeof devname);
2304 if (STRINGP (val))
2306 char *arg = SSDATA (val);
2307 int len = min (strlen (arg), IFNAMSIZ);
2308 memcpy (devname, arg, len);
2310 else if (!NILP (val))
2311 error ("Bad option value for %s", name);
2312 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2313 devname, IFNAMSIZ);
2314 break;
2316 #endif
2318 #ifdef SO_LINGER
2319 case SOPT_LINGER:
2321 struct linger linger;
2323 linger.l_onoff = 1;
2324 linger.l_linger = 0;
2325 if (INTEGERP (val))
2326 linger.l_linger = XINT (val);
2327 else
2328 linger.l_onoff = NILP (val) ? 0 : 1;
2329 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2330 &linger, sizeof (linger));
2331 break;
2333 #endif
2335 default:
2336 return 0;
2339 if (ret < 0)
2340 report_file_error ("Cannot set network option",
2341 Fcons (opt, Fcons (val, Qnil)));
2342 return (1 << sopt->optbit);
2346 DEFUN ("set-network-process-option",
2347 Fset_network_process_option, Sset_network_process_option,
2348 3, 4, 0,
2349 doc: /* For network process PROCESS set option OPTION to value VALUE.
2350 See `make-network-process' for a list of options and values.
2351 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2352 OPTION is not a supported option, return nil instead; otherwise return t. */)
2353 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2355 int s;
2356 struct Lisp_Process *p;
2358 CHECK_PROCESS (process);
2359 p = XPROCESS (process);
2360 if (!NETCONN1_P (p))
2361 error ("Process is not a network process");
2363 s = p->infd;
2364 if (s < 0)
2365 error ("Process is not running");
2367 if (set_socket_option (s, option, value))
2369 p->childp = Fplist_put (p->childp, option, value);
2370 return Qt;
2373 if (NILP (no_error))
2374 error ("Unknown or unsupported option");
2376 return Qnil;
2380 DEFUN ("serial-process-configure",
2381 Fserial_process_configure,
2382 Sserial_process_configure,
2383 0, MANY, 0,
2384 doc: /* Configure speed, bytesize, etc. of a serial process.
2386 Arguments are specified as keyword/argument pairs. Attributes that
2387 are not given are re-initialized from the process's current
2388 configuration (available via the function `process-contact') or set to
2389 reasonable default values. The following arguments are defined:
2391 :process PROCESS
2392 :name NAME
2393 :buffer BUFFER
2394 :port PORT
2395 -- Any of these arguments can be given to identify the process that is
2396 to be configured. If none of these arguments is given, the current
2397 buffer's process is used.
2399 :speed SPEED -- SPEED is the speed of the serial port in bits per
2400 second, also called baud rate. Any value can be given for SPEED, but
2401 most serial ports work only at a few defined values between 1200 and
2402 115200, with 9600 being the most common value. If SPEED is nil, the
2403 serial port is not configured any further, i.e., all other arguments
2404 are ignored. This may be useful for special serial ports such as
2405 Bluetooth-to-serial converters which can only be configured through AT
2406 commands. A value of nil for SPEED can be used only when passed
2407 through `make-serial-process' or `serial-term'.
2409 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2410 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2412 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2413 `odd' (use odd parity), or the symbol `even' (use even parity). If
2414 PARITY is not given, no parity is used.
2416 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2417 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2418 is not given or nil, 1 stopbit is used.
2420 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2421 flowcontrol to be used, which is either nil (don't use flowcontrol),
2422 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2423 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2424 flowcontrol is used.
2426 `serial-process-configure' is called by `make-serial-process' for the
2427 initial configuration of the serial port.
2429 Examples:
2431 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2433 \(serial-process-configure
2434 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2436 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2438 usage: (serial-process-configure &rest ARGS) */)
2439 (size_t nargs, Lisp_Object *args)
2441 struct Lisp_Process *p;
2442 Lisp_Object contact = Qnil;
2443 Lisp_Object proc = Qnil;
2444 struct gcpro gcpro1;
2446 contact = Flist (nargs, args);
2447 GCPRO1 (contact);
2449 proc = Fplist_get (contact, QCprocess);
2450 if (NILP (proc))
2451 proc = Fplist_get (contact, QCname);
2452 if (NILP (proc))
2453 proc = Fplist_get (contact, QCbuffer);
2454 if (NILP (proc))
2455 proc = Fplist_get (contact, QCport);
2456 proc = get_process (proc);
2457 p = XPROCESS (proc);
2458 if (!EQ (p->type, Qserial))
2459 error ("Not a serial process");
2461 if (NILP (Fplist_get (p->childp, QCspeed)))
2463 UNGCPRO;
2464 return Qnil;
2467 serial_configure (p, contact);
2469 UNGCPRO;
2470 return Qnil;
2473 /* Used by make-serial-process to recover from errors. */
2474 static Lisp_Object
2475 make_serial_process_unwind (Lisp_Object proc)
2477 if (!PROCESSP (proc))
2478 abort ();
2479 remove_process (proc);
2480 return Qnil;
2483 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2484 0, MANY, 0,
2485 doc: /* Create and return a serial port process.
2487 In Emacs, serial port connections are represented by process objects,
2488 so input and output work as for subprocesses, and `delete-process'
2489 closes a serial port connection. However, a serial process has no
2490 process id, it cannot be signaled, and the status codes are different
2491 from normal processes.
2493 `make-serial-process' creates a process and a buffer, on which you
2494 probably want to use `process-send-string'. Try \\[serial-term] for
2495 an interactive terminal. See below for examples.
2497 Arguments are specified as keyword/argument pairs. The following
2498 arguments are defined:
2500 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2501 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2502 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2503 the backslashes in strings).
2505 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2506 which is called by `make-serial-process'.
2508 :name NAME -- NAME is the name of the process. If NAME is not given,
2509 the value of PORT is used.
2511 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2512 with the process. Process output goes at the end of that buffer,
2513 unless you specify an output stream or filter function to handle the
2514 output. If BUFFER is not given, the value of NAME is used.
2516 :coding CODING -- If CODING is a symbol, it specifies the coding
2517 system used for both reading and writing for this process. If CODING
2518 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2519 ENCODING is used for writing.
2521 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2522 the process is running. If BOOL is not given, query before exiting.
2524 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2525 In the stopped state, a serial process does not accept incoming data,
2526 but you can send outgoing data. The stopped state is cleared by
2527 `continue-process' and set by `stop-process'.
2529 :filter FILTER -- Install FILTER as the process filter.
2531 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2533 :plist PLIST -- Install PLIST as the initial plist of the process.
2535 :speed
2536 :bytesize
2537 :parity
2538 :stopbits
2539 :flowcontrol
2540 -- These arguments are handled by `serial-process-configure', which is
2541 called by `make-serial-process'.
2543 The original argument list, possibly modified by later configuration,
2544 is available via the function `process-contact'.
2546 Examples:
2548 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2550 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2552 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2554 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2556 usage: (make-serial-process &rest ARGS) */)
2557 (size_t nargs, Lisp_Object *args)
2559 int fd = -1;
2560 Lisp_Object proc, contact, port;
2561 struct Lisp_Process *p;
2562 struct gcpro gcpro1;
2563 Lisp_Object name, buffer;
2564 Lisp_Object tem, val;
2565 int specpdl_count = -1;
2567 if (nargs == 0)
2568 return Qnil;
2570 contact = Flist (nargs, args);
2571 GCPRO1 (contact);
2573 port = Fplist_get (contact, QCport);
2574 if (NILP (port))
2575 error ("No port specified");
2576 CHECK_STRING (port);
2578 if (NILP (Fplist_member (contact, QCspeed)))
2579 error (":speed not specified");
2580 if (!NILP (Fplist_get (contact, QCspeed)))
2581 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2583 name = Fplist_get (contact, QCname);
2584 if (NILP (name))
2585 name = port;
2586 CHECK_STRING (name);
2587 proc = make_process (name);
2588 specpdl_count = SPECPDL_INDEX ();
2589 record_unwind_protect (make_serial_process_unwind, proc);
2590 p = XPROCESS (proc);
2592 fd = serial_open (SSDATA (port));
2593 p->infd = fd;
2594 p->outfd = fd;
2595 if (fd > max_process_desc)
2596 max_process_desc = fd;
2597 chan_process[fd] = proc;
2599 buffer = Fplist_get (contact, QCbuffer);
2600 if (NILP (buffer))
2601 buffer = name;
2602 buffer = Fget_buffer_create (buffer);
2603 p->buffer = buffer;
2605 p->childp = contact;
2606 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
2607 p->type = Qserial;
2608 p->sentinel = Fplist_get (contact, QCsentinel);
2609 p->filter = Fplist_get (contact, QCfilter);
2610 p->log = Qnil;
2611 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2612 p->kill_without_query = 1;
2613 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2614 p->command = Qt;
2615 p->pty_flag = 0;
2617 if (!EQ (p->command, Qt))
2619 FD_SET (fd, &input_wait_mask);
2620 FD_SET (fd, &non_keyboard_wait_mask);
2623 if (BUFFERP (buffer))
2625 set_marker_both (p->mark, buffer,
2626 BUF_ZV (XBUFFER (buffer)),
2627 BUF_ZV_BYTE (XBUFFER (buffer)));
2630 tem = Fplist_member (contact, QCcoding);
2631 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2632 tem = Qnil;
2634 val = Qnil;
2635 if (!NILP (tem))
2637 val = XCAR (XCDR (tem));
2638 if (CONSP (val))
2639 val = XCAR (val);
2641 else if (!NILP (Vcoding_system_for_read))
2642 val = Vcoding_system_for_read;
2643 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2644 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2645 val = Qnil;
2646 p->decode_coding_system = val;
2648 val = Qnil;
2649 if (!NILP (tem))
2651 val = XCAR (XCDR (tem));
2652 if (CONSP (val))
2653 val = XCDR (val);
2655 else if (!NILP (Vcoding_system_for_write))
2656 val = Vcoding_system_for_write;
2657 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2658 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2659 val = Qnil;
2660 p->encode_coding_system = val;
2662 setup_process_coding_systems (proc);
2663 p->decoding_buf = empty_unibyte_string;
2664 p->decoding_carryover = 0;
2665 p->encoding_buf = empty_unibyte_string;
2666 p->inherit_coding_system_flag
2667 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2669 Fserial_process_configure (nargs, args);
2671 specpdl_ptr = specpdl + specpdl_count;
2673 UNGCPRO;
2674 return proc;
2677 /* Create a network stream/datagram client/server process. Treated
2678 exactly like a normal process when reading and writing. Primary
2679 differences are in status display and process deletion. A network
2680 connection has no PID; you cannot signal it. All you can do is
2681 stop/continue it and deactivate/close it via delete-process */
2683 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2684 0, MANY, 0,
2685 doc: /* Create and return a network server or client process.
2687 In Emacs, network connections are represented by process objects, so
2688 input and output work as for subprocesses and `delete-process' closes
2689 a network connection. However, a network process has no process id,
2690 it cannot be signaled, and the status codes are different from normal
2691 processes.
2693 Arguments are specified as keyword/argument pairs. The following
2694 arguments are defined:
2696 :name NAME -- NAME is name for process. It is modified if necessary
2697 to make it unique.
2699 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2700 with the process. Process output goes at end of that buffer, unless
2701 you specify an output stream or filter function to handle the output.
2702 BUFFER may be also nil, meaning that this process is not associated
2703 with any buffer.
2705 :host HOST -- HOST is name of the host to connect to, or its IP
2706 address. The symbol `local' specifies the local host. If specified
2707 for a server process, it must be a valid name or address for the local
2708 host, and only clients connecting to that address will be accepted.
2710 :service SERVICE -- SERVICE is name of the service desired, or an
2711 integer specifying a port number to connect to. If SERVICE is t,
2712 a random port number is selected for the server. (If Emacs was
2713 compiled with getaddrinfo, a port number can also be specified as a
2714 string, e.g. "80", as well as an integer. This is not portable.)
2716 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2717 stream type connection, `datagram' creates a datagram type connection,
2718 `seqpacket' creates a reliable datagram connection.
2720 :family FAMILY -- FAMILY is the address (and protocol) family for the
2721 service specified by HOST and SERVICE. The default (nil) is to use
2722 whatever address family (IPv4 or IPv6) that is defined for the host
2723 and port number specified by HOST and SERVICE. Other address families
2724 supported are:
2725 local -- for a local (i.e. UNIX) address specified by SERVICE.
2726 ipv4 -- use IPv4 address family only.
2727 ipv6 -- use IPv6 address family only.
2729 :local ADDRESS -- ADDRESS is the local address used for the connection.
2730 This parameter is ignored when opening a client process. When specified
2731 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2733 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2734 connection. This parameter is ignored when opening a stream server
2735 process. For a datagram server process, it specifies the initial
2736 setting of the remote datagram address. When specified for a client
2737 process, the FAMILY, HOST, and SERVICE args are ignored.
2739 The format of ADDRESS depends on the address family:
2740 - An IPv4 address is represented as an vector of integers [A B C D P]
2741 corresponding to numeric IP address A.B.C.D and port number P.
2742 - A local address is represented as a string with the address in the
2743 local address space.
2744 - An "unsupported family" address is represented by a cons (F . AV)
2745 where F is the family number and AV is a vector containing the socket
2746 address data with one element per address data byte. Do not rely on
2747 this format in portable code, as it may depend on implementation
2748 defined constants, data sizes, and data structure alignment.
2750 :coding CODING -- If CODING is a symbol, it specifies the coding
2751 system used for both reading and writing for this process. If CODING
2752 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2753 ENCODING is used for writing.
2755 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2756 return without waiting for the connection to complete; instead, the
2757 sentinel function will be called with second arg matching "open" (if
2758 successful) or "failed" when the connect completes. Default is to use
2759 a blocking connect (i.e. wait) for stream type connections.
2761 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2762 running when Emacs is exited.
2764 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2765 In the stopped state, a server process does not accept new
2766 connections, and a client process does not handle incoming traffic.
2767 The stopped state is cleared by `continue-process' and set by
2768 `stop-process'.
2770 :filter FILTER -- Install FILTER as the process filter.
2772 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2773 process filter are multibyte, otherwise they are unibyte.
2774 If this keyword is not specified, the strings are multibyte if
2775 `default-enable-multibyte-characters' is non-nil.
2777 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2779 :log LOG -- Install LOG as the server process log function. This
2780 function is called when the server accepts a network connection from a
2781 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2782 is the server process, CLIENT is the new process for the connection,
2783 and MESSAGE is a string.
2785 :plist PLIST -- Install PLIST as the new process' initial plist.
2787 :server QLEN -- if QLEN is non-nil, create a server process for the
2788 specified FAMILY, SERVICE, and connection type (stream or datagram).
2789 If QLEN is an integer, it is used as the max. length of the server's
2790 pending connection queue (also known as the backlog); the default
2791 queue length is 5. Default is to create a client process.
2793 The following network options can be specified for this connection:
2795 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2796 :dontroute BOOL -- Only send to directly connected hosts.
2797 :keepalive BOOL -- Send keep-alive messages on network stream.
2798 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2799 :oobinline BOOL -- Place out-of-band data in receive data stream.
2800 :priority INT -- Set protocol defined priority for sent packets.
2801 :reuseaddr BOOL -- Allow reusing a recently used local address
2802 (this is allowed by default for a server process).
2803 :bindtodevice NAME -- bind to interface NAME. Using this may require
2804 special privileges on some systems.
2806 Consult the relevant system programmer's manual pages for more
2807 information on using these options.
2810 A server process will listen for and accept connections from clients.
2811 When a client connection is accepted, a new network process is created
2812 for the connection with the following parameters:
2814 - The client's process name is constructed by concatenating the server
2815 process' NAME and a client identification string.
2816 - If the FILTER argument is non-nil, the client process will not get a
2817 separate process buffer; otherwise, the client's process buffer is a newly
2818 created buffer named after the server process' BUFFER name or process
2819 NAME concatenated with the client identification string.
2820 - The connection type and the process filter and sentinel parameters are
2821 inherited from the server process' TYPE, FILTER and SENTINEL.
2822 - The client process' contact info is set according to the client's
2823 addressing information (typically an IP address and a port number).
2824 - The client process' plist is initialized from the server's plist.
2826 Notice that the FILTER and SENTINEL args are never used directly by
2827 the server process. Also, the BUFFER argument is not used directly by
2828 the server process, but via the optional :log function, accepted (and
2829 failed) connections may be logged in the server process' buffer.
2831 The original argument list, modified with the actual connection
2832 information, is available via the `process-contact' function.
2834 usage: (make-network-process &rest ARGS) */)
2835 (size_t nargs, Lisp_Object *args)
2837 Lisp_Object proc;
2838 Lisp_Object contact;
2839 struct Lisp_Process *p;
2840 #ifdef HAVE_GETADDRINFO
2841 struct addrinfo ai, *res, *lres;
2842 struct addrinfo hints;
2843 const char *portstring;
2844 char portbuf[128];
2845 #else /* HAVE_GETADDRINFO */
2846 struct _emacs_addrinfo
2848 int ai_family;
2849 int ai_socktype;
2850 int ai_protocol;
2851 int ai_addrlen;
2852 struct sockaddr *ai_addr;
2853 struct _emacs_addrinfo *ai_next;
2854 } ai, *res, *lres;
2855 #endif /* HAVE_GETADDRINFO */
2856 struct sockaddr_in address_in;
2857 #ifdef HAVE_LOCAL_SOCKETS
2858 struct sockaddr_un address_un;
2859 #endif
2860 int port;
2861 int ret = 0;
2862 int xerrno = 0;
2863 int s = -1, outch, inch;
2864 struct gcpro gcpro1;
2865 int count = SPECPDL_INDEX ();
2866 int count1;
2867 Lisp_Object QCaddress; /* one of QClocal or QCremote */
2868 Lisp_Object tem;
2869 Lisp_Object name, buffer, host, service, address;
2870 Lisp_Object filter, sentinel;
2871 int is_non_blocking_client = 0;
2872 int is_server = 0, backlog = 5;
2873 int socktype;
2874 int family = -1;
2876 if (nargs == 0)
2877 return Qnil;
2879 /* Save arguments for process-contact and clone-process. */
2880 contact = Flist (nargs, args);
2881 GCPRO1 (contact);
2883 #ifdef WINDOWSNT
2884 /* Ensure socket support is loaded if available. */
2885 init_winsock (TRUE);
2886 #endif
2888 /* :type TYPE (nil: stream, datagram */
2889 tem = Fplist_get (contact, QCtype);
2890 if (NILP (tem))
2891 socktype = SOCK_STREAM;
2892 #ifdef DATAGRAM_SOCKETS
2893 else if (EQ (tem, Qdatagram))
2894 socktype = SOCK_DGRAM;
2895 #endif
2896 #ifdef HAVE_SEQPACKET
2897 else if (EQ (tem, Qseqpacket))
2898 socktype = SOCK_SEQPACKET;
2899 #endif
2900 else
2901 error ("Unsupported connection type");
2903 /* :server BOOL */
2904 tem = Fplist_get (contact, QCserver);
2905 if (!NILP (tem))
2907 /* Don't support network sockets when non-blocking mode is
2908 not available, since a blocked Emacs is not useful. */
2909 #if !defined(O_NONBLOCK) && !defined(O_NDELAY)
2910 error ("Network servers not supported");
2911 #else
2912 is_server = 1;
2913 if (INTEGERP (tem))
2914 backlog = XINT (tem);
2915 #endif
2918 /* Make QCaddress an alias for :local (server) or :remote (client). */
2919 QCaddress = is_server ? QClocal : QCremote;
2921 /* :nowait BOOL */
2922 if (!is_server && socktype != SOCK_DGRAM
2923 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
2925 #ifndef NON_BLOCKING_CONNECT
2926 error ("Non-blocking connect not supported");
2927 #else
2928 is_non_blocking_client = 1;
2929 #endif
2932 name = Fplist_get (contact, QCname);
2933 buffer = Fplist_get (contact, QCbuffer);
2934 filter = Fplist_get (contact, QCfilter);
2935 sentinel = Fplist_get (contact, QCsentinel);
2937 CHECK_STRING (name);
2939 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
2940 ai.ai_socktype = socktype;
2941 ai.ai_protocol = 0;
2942 ai.ai_next = NULL;
2943 res = &ai;
2945 /* :local ADDRESS or :remote ADDRESS */
2946 address = Fplist_get (contact, QCaddress);
2947 if (!NILP (address))
2949 host = service = Qnil;
2951 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
2952 error ("Malformed :address");
2953 ai.ai_family = family;
2954 ai.ai_addr = alloca (ai.ai_addrlen);
2955 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
2956 goto open_socket;
2959 /* :family FAMILY -- nil (for Inet), local, or integer. */
2960 tem = Fplist_get (contact, QCfamily);
2961 if (NILP (tem))
2963 #if defined(HAVE_GETADDRINFO) && defined(AF_INET6)
2964 family = AF_UNSPEC;
2965 #else
2966 family = AF_INET;
2967 #endif
2969 #ifdef HAVE_LOCAL_SOCKETS
2970 else if (EQ (tem, Qlocal))
2971 family = AF_LOCAL;
2972 #endif
2973 #ifdef AF_INET6
2974 else if (EQ (tem, Qipv6))
2975 family = AF_INET6;
2976 #endif
2977 else if (EQ (tem, Qipv4))
2978 family = AF_INET;
2979 else if (INTEGERP (tem))
2980 family = XINT (tem);
2981 else
2982 error ("Unknown address family");
2984 ai.ai_family = family;
2986 /* :service SERVICE -- string, integer (port number), or t (random port). */
2987 service = Fplist_get (contact, QCservice);
2989 /* :host HOST -- hostname, ip address, or 'local for localhost. */
2990 host = Fplist_get (contact, QChost);
2991 if (!NILP (host))
2993 if (EQ (host, Qlocal))
2994 /* Depending on setup, "localhost" may map to different IPv4 and/or
2995 IPv6 addresses, so it's better to be explicit. (Bug#6781) */
2996 host = build_string ("127.0.0.1");
2997 CHECK_STRING (host);
3000 #ifdef HAVE_LOCAL_SOCKETS
3001 if (family == AF_LOCAL)
3003 if (!NILP (host))
3005 message (":family local ignores the :host \"%s\" property",
3006 SDATA (host));
3007 contact = Fplist_put (contact, QChost, Qnil);
3008 host = Qnil;
3010 CHECK_STRING (service);
3011 memset (&address_un, 0, sizeof address_un);
3012 address_un.sun_family = AF_LOCAL;
3013 strncpy (address_un.sun_path, SSDATA (service), sizeof address_un.sun_path);
3014 ai.ai_addr = (struct sockaddr *) &address_un;
3015 ai.ai_addrlen = sizeof address_un;
3016 goto open_socket;
3018 #endif
3020 /* Slow down polling to every ten seconds.
3021 Some kernels have a bug which causes retrying connect to fail
3022 after a connect. Polling can interfere with gethostbyname too. */
3023 #ifdef POLL_FOR_INPUT
3024 if (socktype != SOCK_DGRAM)
3026 record_unwind_protect (unwind_stop_other_atimers, Qnil);
3027 bind_polling_period (10);
3029 #endif
3031 #ifdef HAVE_GETADDRINFO
3032 /* If we have a host, use getaddrinfo to resolve both host and service.
3033 Otherwise, use getservbyname to lookup the service. */
3034 if (!NILP (host))
3037 /* SERVICE can either be a string or int.
3038 Convert to a C string for later use by getaddrinfo. */
3039 if (EQ (service, Qt))
3040 portstring = "0";
3041 else if (INTEGERP (service))
3043 sprintf (portbuf, "%"pI"d", XINT (service));
3044 portstring = portbuf;
3046 else
3048 CHECK_STRING (service);
3049 portstring = SSDATA (service);
3052 immediate_quit = 1;
3053 QUIT;
3054 memset (&hints, 0, sizeof (hints));
3055 hints.ai_flags = 0;
3056 hints.ai_family = family;
3057 hints.ai_socktype = socktype;
3058 hints.ai_protocol = 0;
3060 #ifdef HAVE_RES_INIT
3061 res_init ();
3062 #endif
3064 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3065 if (ret)
3066 #ifdef HAVE_GAI_STRERROR
3067 error ("%s/%s %s", SSDATA (host), portstring, gai_strerror (ret));
3068 #else
3069 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3070 #endif
3071 immediate_quit = 0;
3073 goto open_socket;
3075 #endif /* HAVE_GETADDRINFO */
3077 /* We end up here if getaddrinfo is not defined, or in case no hostname
3078 has been specified (e.g. for a local server process). */
3080 if (EQ (service, Qt))
3081 port = 0;
3082 else if (INTEGERP (service))
3083 port = htons ((unsigned short) XINT (service));
3084 else
3086 struct servent *svc_info;
3087 CHECK_STRING (service);
3088 svc_info = getservbyname (SSDATA (service),
3089 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3090 if (svc_info == 0)
3091 error ("Unknown service: %s", SDATA (service));
3092 port = svc_info->s_port;
3095 memset (&address_in, 0, sizeof address_in);
3096 address_in.sin_family = family;
3097 address_in.sin_addr.s_addr = INADDR_ANY;
3098 address_in.sin_port = port;
3100 #ifndef HAVE_GETADDRINFO
3101 if (!NILP (host))
3103 struct hostent *host_info_ptr;
3105 /* gethostbyname may fail with TRY_AGAIN, but we don't honour that,
3106 as it may `hang' Emacs for a very long time. */
3107 immediate_quit = 1;
3108 QUIT;
3110 #ifdef HAVE_RES_INIT
3111 res_init ();
3112 #endif
3114 host_info_ptr = gethostbyname (SDATA (host));
3115 immediate_quit = 0;
3117 if (host_info_ptr)
3119 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3120 host_info_ptr->h_length);
3121 family = host_info_ptr->h_addrtype;
3122 address_in.sin_family = family;
3124 else
3125 /* Attempt to interpret host as numeric inet address */
3127 unsigned long numeric_addr;
3128 numeric_addr = inet_addr (SSDATA (host));
3129 if (numeric_addr == -1)
3130 error ("Unknown host \"%s\"", SDATA (host));
3132 memcpy (&address_in.sin_addr, &numeric_addr,
3133 sizeof (address_in.sin_addr));
3137 #endif /* not HAVE_GETADDRINFO */
3139 ai.ai_family = family;
3140 ai.ai_addr = (struct sockaddr *) &address_in;
3141 ai.ai_addrlen = sizeof address_in;
3143 open_socket:
3145 /* Do this in case we never enter the for-loop below. */
3146 count1 = SPECPDL_INDEX ();
3147 s = -1;
3149 for (lres = res; lres; lres = lres->ai_next)
3151 size_t optn;
3152 int optbits;
3154 #ifdef WINDOWSNT
3155 retry_connect:
3156 #endif
3158 s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
3159 if (s < 0)
3161 xerrno = errno;
3162 continue;
3165 #ifdef DATAGRAM_SOCKETS
3166 if (!is_server && socktype == SOCK_DGRAM)
3167 break;
3168 #endif /* DATAGRAM_SOCKETS */
3170 #ifdef NON_BLOCKING_CONNECT
3171 if (is_non_blocking_client)
3173 #ifdef O_NONBLOCK
3174 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3175 #else
3176 ret = fcntl (s, F_SETFL, O_NDELAY);
3177 #endif
3178 if (ret < 0)
3180 xerrno = errno;
3181 emacs_close (s);
3182 s = -1;
3183 continue;
3186 #endif
3188 /* Make us close S if quit. */
3189 record_unwind_protect (close_file_unwind, make_number (s));
3191 /* Parse network options in the arg list.
3192 We simply ignore anything which isn't a known option (including other keywords).
3193 An error is signaled if setting a known option fails. */
3194 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3195 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3197 if (is_server)
3199 /* Configure as a server socket. */
3201 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3202 explicit :reuseaddr key to override this. */
3203 #ifdef HAVE_LOCAL_SOCKETS
3204 if (family != AF_LOCAL)
3205 #endif
3206 if (!(optbits & (1 << OPIX_REUSEADDR)))
3208 int optval = 1;
3209 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3210 report_file_error ("Cannot set reuse option on server socket", Qnil);
3213 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3214 report_file_error ("Cannot bind server socket", Qnil);
3216 #ifdef HAVE_GETSOCKNAME
3217 if (EQ (service, Qt))
3219 struct sockaddr_in sa1;
3220 socklen_t len1 = sizeof (sa1);
3221 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3223 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3224 service = make_number (ntohs (sa1.sin_port));
3225 contact = Fplist_put (contact, QCservice, service);
3228 #endif
3230 if (socktype != SOCK_DGRAM && listen (s, backlog))
3231 report_file_error ("Cannot listen on server socket", Qnil);
3233 break;
3236 immediate_quit = 1;
3237 QUIT;
3239 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3240 xerrno = errno;
3242 if (ret == 0 || xerrno == EISCONN)
3244 /* The unwind-protect will be discarded afterwards.
3245 Likewise for immediate_quit. */
3246 break;
3249 #ifdef NON_BLOCKING_CONNECT
3250 #ifdef EINPROGRESS
3251 if (is_non_blocking_client && xerrno == EINPROGRESS)
3252 break;
3253 #else
3254 #ifdef EWOULDBLOCK
3255 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3256 break;
3257 #endif
3258 #endif
3259 #endif
3261 #ifndef WINDOWSNT
3262 if (xerrno == EINTR)
3264 /* Unlike most other syscalls connect() cannot be called
3265 again. (That would return EALREADY.) The proper way to
3266 wait for completion is select(). */
3267 int sc;
3268 socklen_t len;
3269 SELECT_TYPE fdset;
3270 retry_select:
3271 FD_ZERO (&fdset);
3272 FD_SET (s, &fdset);
3273 QUIT;
3274 sc = select (s + 1, (SELECT_TYPE *)0, &fdset, (SELECT_TYPE *)0,
3275 (EMACS_TIME *)0);
3276 if (sc == -1)
3278 if (errno == EINTR)
3279 goto retry_select;
3280 else
3281 report_file_error ("select failed", Qnil);
3283 eassert (sc > 0);
3285 len = sizeof xerrno;
3286 eassert (FD_ISSET (s, &fdset));
3287 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) == -1)
3288 report_file_error ("getsockopt failed", Qnil);
3289 if (xerrno)
3290 errno = xerrno, report_file_error ("error during connect", Qnil);
3291 else
3292 break;
3294 #endif /* !WINDOWSNT */
3296 immediate_quit = 0;
3298 /* Discard the unwind protect closing S. */
3299 specpdl_ptr = specpdl + count1;
3300 emacs_close (s);
3301 s = -1;
3303 #ifdef WINDOWSNT
3304 if (xerrno == EINTR)
3305 goto retry_connect;
3306 #endif
3309 if (s >= 0)
3311 #ifdef DATAGRAM_SOCKETS
3312 if (socktype == SOCK_DGRAM)
3314 if (datagram_address[s].sa)
3315 abort ();
3316 datagram_address[s].sa = (struct sockaddr *) xmalloc (lres->ai_addrlen);
3317 datagram_address[s].len = lres->ai_addrlen;
3318 if (is_server)
3320 Lisp_Object remote;
3321 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3322 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3324 int rfamily, rlen;
3325 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3326 if (rfamily == lres->ai_family && rlen == lres->ai_addrlen)
3327 conv_lisp_to_sockaddr (rfamily, remote,
3328 datagram_address[s].sa, rlen);
3331 else
3332 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3334 #endif
3335 contact = Fplist_put (contact, QCaddress,
3336 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3337 #ifdef HAVE_GETSOCKNAME
3338 if (!is_server)
3340 struct sockaddr_in sa1;
3341 socklen_t len1 = sizeof (sa1);
3342 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3343 contact = Fplist_put (contact, QClocal,
3344 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3346 #endif
3349 immediate_quit = 0;
3351 #ifdef HAVE_GETADDRINFO
3352 if (res != &ai)
3354 BLOCK_INPUT;
3355 freeaddrinfo (res);
3356 UNBLOCK_INPUT;
3358 #endif
3360 /* Discard the unwind protect for closing S, if any. */
3361 specpdl_ptr = specpdl + count1;
3363 /* Unwind bind_polling_period and request_sigio. */
3364 unbind_to (count, Qnil);
3366 if (s < 0)
3368 /* If non-blocking got this far - and failed - assume non-blocking is
3369 not supported after all. This is probably a wrong assumption, but
3370 the normal blocking calls to open-network-stream handles this error
3371 better. */
3372 if (is_non_blocking_client)
3373 return Qnil;
3375 errno = xerrno;
3376 if (is_server)
3377 report_file_error ("make server process failed", contact);
3378 else
3379 report_file_error ("make client process failed", contact);
3382 inch = s;
3383 outch = s;
3385 if (!NILP (buffer))
3386 buffer = Fget_buffer_create (buffer);
3387 proc = make_process (name);
3389 chan_process[inch] = proc;
3391 #ifdef O_NONBLOCK
3392 fcntl (inch, F_SETFL, O_NONBLOCK);
3393 #else
3394 #ifdef O_NDELAY
3395 fcntl (inch, F_SETFL, O_NDELAY);
3396 #endif
3397 #endif
3399 p = XPROCESS (proc);
3401 p->childp = contact;
3402 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
3403 p->type = Qnetwork;
3405 p->buffer = buffer;
3406 p->sentinel = sentinel;
3407 p->filter = filter;
3408 p->log = Fplist_get (contact, QClog);
3409 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3410 p->kill_without_query = 1;
3411 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3412 p->command = Qt;
3413 p->pid = 0;
3414 p->infd = inch;
3415 p->outfd = outch;
3416 if (is_server && socktype != SOCK_DGRAM)
3417 p->status = Qlisten;
3419 /* Make the process marker point into the process buffer (if any). */
3420 if (BUFFERP (buffer))
3421 set_marker_both (p->mark, buffer,
3422 BUF_ZV (XBUFFER (buffer)),
3423 BUF_ZV_BYTE (XBUFFER (buffer)));
3425 #ifdef NON_BLOCKING_CONNECT
3426 if (is_non_blocking_client)
3428 /* We may get here if connect did succeed immediately. However,
3429 in that case, we still need to signal this like a non-blocking
3430 connection. */
3431 p->status = Qconnect;
3432 if (!FD_ISSET (inch, &connect_wait_mask))
3434 FD_SET (inch, &connect_wait_mask);
3435 FD_SET (inch, &write_mask);
3436 num_pending_connects++;
3439 else
3440 #endif
3441 /* A server may have a client filter setting of Qt, but it must
3442 still listen for incoming connects unless it is stopped. */
3443 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3444 || (EQ (p->status, Qlisten) && NILP (p->command)))
3446 FD_SET (inch, &input_wait_mask);
3447 FD_SET (inch, &non_keyboard_wait_mask);
3450 if (inch > max_process_desc)
3451 max_process_desc = inch;
3453 tem = Fplist_member (contact, QCcoding);
3454 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3455 tem = Qnil; /* No error message (too late!). */
3458 /* Setup coding systems for communicating with the network stream. */
3459 struct gcpro inner_gcpro1;
3460 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3461 Lisp_Object coding_systems = Qt;
3462 Lisp_Object fargs[5], val;
3464 if (!NILP (tem))
3466 val = XCAR (XCDR (tem));
3467 if (CONSP (val))
3468 val = XCAR (val);
3470 else if (!NILP (Vcoding_system_for_read))
3471 val = Vcoding_system_for_read;
3472 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3473 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3474 /* We dare not decode end-of-line format by setting VAL to
3475 Qraw_text, because the existing Emacs Lisp libraries
3476 assume that they receive bare code including a sequene of
3477 CR LF. */
3478 val = Qnil;
3479 else
3481 if (NILP (host) || NILP (service))
3482 coding_systems = Qnil;
3483 else
3485 fargs[0] = Qopen_network_stream, fargs[1] = name,
3486 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3487 GCPRO1_VAR (proc, inner_gcpro);
3488 coding_systems = Ffind_operation_coding_system (5, fargs);
3489 UNGCPRO_VAR (inner_gcpro);
3491 if (CONSP (coding_systems))
3492 val = XCAR (coding_systems);
3493 else if (CONSP (Vdefault_process_coding_system))
3494 val = XCAR (Vdefault_process_coding_system);
3495 else
3496 val = Qnil;
3498 p->decode_coding_system = val;
3500 if (!NILP (tem))
3502 val = XCAR (XCDR (tem));
3503 if (CONSP (val))
3504 val = XCDR (val);
3506 else if (!NILP (Vcoding_system_for_write))
3507 val = Vcoding_system_for_write;
3508 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3509 val = Qnil;
3510 else
3512 if (EQ (coding_systems, Qt))
3514 if (NILP (host) || NILP (service))
3515 coding_systems = Qnil;
3516 else
3518 fargs[0] = Qopen_network_stream, fargs[1] = name,
3519 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3520 GCPRO1_VAR (proc, inner_gcpro);
3521 coding_systems = Ffind_operation_coding_system (5, fargs);
3522 UNGCPRO_VAR (inner_gcpro);
3525 if (CONSP (coding_systems))
3526 val = XCDR (coding_systems);
3527 else if (CONSP (Vdefault_process_coding_system))
3528 val = XCDR (Vdefault_process_coding_system);
3529 else
3530 val = Qnil;
3532 p->encode_coding_system = val;
3534 setup_process_coding_systems (proc);
3536 p->decoding_buf = empty_unibyte_string;
3537 p->decoding_carryover = 0;
3538 p->encoding_buf = empty_unibyte_string;
3540 p->inherit_coding_system_flag
3541 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3543 UNGCPRO;
3544 return proc;
3548 #if defined(HAVE_NET_IF_H)
3550 #ifdef SIOCGIFCONF
3551 DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3552 doc: /* Return an alist of all network interfaces and their network address.
3553 Each element is a cons, the car of which is a string containing the
3554 interface name, and the cdr is the network address in internal
3555 format; see the description of ADDRESS in `make-network-process'. */)
3556 (void)
3558 struct ifconf ifconf;
3559 struct ifreq *ifreqs = NULL;
3560 int ifaces = 0;
3561 int buf_size, s;
3562 Lisp_Object res;
3564 s = socket (AF_INET, SOCK_STREAM, 0);
3565 if (s < 0)
3566 return Qnil;
3568 again:
3569 ifaces += 25;
3570 buf_size = ifaces * sizeof (ifreqs[0]);
3571 ifreqs = (struct ifreq *)xrealloc(ifreqs, buf_size);
3572 if (!ifreqs)
3574 close (s);
3575 return Qnil;
3578 ifconf.ifc_len = buf_size;
3579 ifconf.ifc_req = ifreqs;
3580 if (ioctl (s, SIOCGIFCONF, &ifconf))
3582 close (s);
3583 return Qnil;
3586 if (ifconf.ifc_len == buf_size)
3587 goto again;
3589 close (s);
3590 ifaces = ifconf.ifc_len / sizeof (ifreqs[0]);
3592 res = Qnil;
3593 while (--ifaces >= 0)
3595 struct ifreq *ifq = &ifreqs[ifaces];
3596 char namebuf[sizeof (ifq->ifr_name) + 1];
3597 if (ifq->ifr_addr.sa_family != AF_INET)
3598 continue;
3599 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3600 namebuf[sizeof (ifq->ifr_name)] = 0;
3601 res = Fcons (Fcons (build_string (namebuf),
3602 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3603 sizeof (struct sockaddr))),
3604 res);
3607 return res;
3609 #endif /* SIOCGIFCONF */
3611 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
3613 struct ifflag_def {
3614 int flag_bit;
3615 const char *flag_sym;
3618 static const struct ifflag_def ifflag_table[] = {
3619 #ifdef IFF_UP
3620 { IFF_UP, "up" },
3621 #endif
3622 #ifdef IFF_BROADCAST
3623 { IFF_BROADCAST, "broadcast" },
3624 #endif
3625 #ifdef IFF_DEBUG
3626 { IFF_DEBUG, "debug" },
3627 #endif
3628 #ifdef IFF_LOOPBACK
3629 { IFF_LOOPBACK, "loopback" },
3630 #endif
3631 #ifdef IFF_POINTOPOINT
3632 { IFF_POINTOPOINT, "pointopoint" },
3633 #endif
3634 #ifdef IFF_RUNNING
3635 { IFF_RUNNING, "running" },
3636 #endif
3637 #ifdef IFF_NOARP
3638 { IFF_NOARP, "noarp" },
3639 #endif
3640 #ifdef IFF_PROMISC
3641 { IFF_PROMISC, "promisc" },
3642 #endif
3643 #ifdef IFF_NOTRAILERS
3644 { IFF_NOTRAILERS, "notrailers" },
3645 #endif
3646 #ifdef IFF_ALLMULTI
3647 { IFF_ALLMULTI, "allmulti" },
3648 #endif
3649 #ifdef IFF_MASTER
3650 { IFF_MASTER, "master" },
3651 #endif
3652 #ifdef IFF_SLAVE
3653 { IFF_SLAVE, "slave" },
3654 #endif
3655 #ifdef IFF_MULTICAST
3656 { IFF_MULTICAST, "multicast" },
3657 #endif
3658 #ifdef IFF_PORTSEL
3659 { IFF_PORTSEL, "portsel" },
3660 #endif
3661 #ifdef IFF_AUTOMEDIA
3662 { IFF_AUTOMEDIA, "automedia" },
3663 #endif
3664 #ifdef IFF_DYNAMIC
3665 { IFF_DYNAMIC, "dynamic" },
3666 #endif
3667 #ifdef IFF_OACTIVE
3668 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3669 #endif
3670 #ifdef IFF_SIMPLEX
3671 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3672 #endif
3673 #ifdef IFF_LINK0
3674 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3675 #endif
3676 #ifdef IFF_LINK1
3677 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3678 #endif
3679 #ifdef IFF_LINK2
3680 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3681 #endif
3682 { 0, 0 }
3685 DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
3686 doc: /* Return information about network interface named IFNAME.
3687 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3688 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3689 NETMASK is the layer 3 network mask, HWADDR is the layer 2 addres, and
3690 FLAGS is the current flags of the interface. */)
3691 (Lisp_Object ifname)
3693 struct ifreq rq;
3694 Lisp_Object res = Qnil;
3695 Lisp_Object elt;
3696 int s;
3697 int any = 0;
3699 CHECK_STRING (ifname);
3701 memset (rq.ifr_name, 0, sizeof rq.ifr_name);
3702 strncpy (rq.ifr_name, SSDATA (ifname), sizeof (rq.ifr_name));
3704 s = socket (AF_INET, SOCK_STREAM, 0);
3705 if (s < 0)
3706 return Qnil;
3708 elt = Qnil;
3709 #if defined(SIOCGIFFLAGS) && defined(HAVE_STRUCT_IFREQ_IFR_FLAGS)
3710 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3712 int flags = rq.ifr_flags;
3713 const struct ifflag_def *fp;
3714 int fnum;
3716 any = 1;
3717 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3719 if (flags & fp->flag_bit)
3721 elt = Fcons (intern (fp->flag_sym), elt);
3722 flags -= fp->flag_bit;
3725 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
3727 if (flags & 1)
3729 elt = Fcons (make_number (fnum), elt);
3733 #endif
3734 res = Fcons (elt, res);
3736 elt = Qnil;
3737 #if defined(SIOCGIFHWADDR) && defined(HAVE_STRUCT_IFREQ_IFR_HWADDR)
3738 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3740 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3741 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3742 int n;
3744 any = 1;
3745 for (n = 0; n < 6; n++)
3746 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
3747 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3749 #endif
3750 res = Fcons (elt, res);
3752 elt = Qnil;
3753 #if defined(SIOCGIFNETMASK) && (defined(HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined(HAVE_STRUCT_IFREQ_IFR_ADDR))
3754 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
3756 any = 1;
3757 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3758 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
3759 #else
3760 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3761 #endif
3763 #endif
3764 res = Fcons (elt, res);
3766 elt = Qnil;
3767 #if defined(SIOCGIFBRDADDR) && defined(HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3768 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
3770 any = 1;
3771 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
3773 #endif
3774 res = Fcons (elt, res);
3776 elt = Qnil;
3777 #if defined(SIOCGIFADDR) && defined(HAVE_STRUCT_IFREQ_IFR_ADDR)
3778 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
3780 any = 1;
3781 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3783 #endif
3784 res = Fcons (elt, res);
3786 close (s);
3788 return any ? res : Qnil;
3790 #endif
3791 #endif /* defined(HAVE_NET_IF_H) */
3793 /* Turn off input and output for process PROC. */
3795 static void
3796 deactivate_process (Lisp_Object proc)
3798 register int inchannel, outchannel;
3799 register struct Lisp_Process *p = XPROCESS (proc);
3801 inchannel = p->infd;
3802 outchannel = p->outfd;
3804 #ifdef ADAPTIVE_READ_BUFFERING
3805 if (p->read_output_delay > 0)
3807 if (--process_output_delay_count < 0)
3808 process_output_delay_count = 0;
3809 p->read_output_delay = 0;
3810 p->read_output_skip = 0;
3812 #endif
3814 if (inchannel >= 0)
3816 /* Beware SIGCHLD hereabouts. */
3817 flush_pending_output (inchannel);
3818 emacs_close (inchannel);
3819 if (outchannel >= 0 && outchannel != inchannel)
3820 emacs_close (outchannel);
3822 p->infd = -1;
3823 p->outfd = -1;
3824 #ifdef DATAGRAM_SOCKETS
3825 if (DATAGRAM_CHAN_P (inchannel))
3827 xfree (datagram_address[inchannel].sa);
3828 datagram_address[inchannel].sa = 0;
3829 datagram_address[inchannel].len = 0;
3831 #endif
3832 chan_process[inchannel] = Qnil;
3833 FD_CLR (inchannel, &input_wait_mask);
3834 FD_CLR (inchannel, &non_keyboard_wait_mask);
3835 #ifdef NON_BLOCKING_CONNECT
3836 if (FD_ISSET (inchannel, &connect_wait_mask))
3838 FD_CLR (inchannel, &connect_wait_mask);
3839 FD_CLR (inchannel, &write_mask);
3840 if (--num_pending_connects < 0)
3841 abort ();
3843 #endif
3844 if (inchannel == max_process_desc)
3846 int i;
3847 /* We just closed the highest-numbered process input descriptor,
3848 so recompute the highest-numbered one now. */
3849 max_process_desc = 0;
3850 for (i = 0; i < MAXDESC; i++)
3851 if (!NILP (chan_process[i]))
3852 max_process_desc = i;
3858 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
3859 0, 4, 0,
3860 doc: /* Allow any pending output from subprocesses to be read by Emacs.
3861 It is read into the process' buffers or given to their filter functions.
3862 Non-nil arg PROCESS means do not return until some output has been received
3863 from PROCESS.
3865 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
3866 and milliseconds to wait; return after that much time whether or not
3867 there is any subprocess output. If SECONDS is a floating point number,
3868 it specifies a fractional number of seconds to wait.
3869 The MILLISEC argument is obsolete and should be avoided.
3871 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
3872 from PROCESS, suspending reading output from other processes.
3873 If JUST-THIS-ONE is an integer, don't run any timers either.
3874 Return non-nil if we received any output before the timeout expired. */)
3875 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
3877 int secs, usecs = 0;
3879 if (! NILP (process))
3880 CHECK_PROCESS (process);
3881 else
3882 just_this_one = Qnil;
3884 if (!NILP (millisec))
3885 { /* Obsolete calling convention using integers rather than floats. */
3886 CHECK_NUMBER (millisec);
3887 if (NILP (seconds))
3888 seconds = make_float (XINT (millisec) / 1000.0);
3889 else
3891 CHECK_NUMBER (seconds);
3892 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
3896 if (!NILP (seconds))
3898 if (INTEGERP (seconds))
3899 secs = XINT (seconds);
3900 else if (FLOATP (seconds))
3902 double timeout = XFLOAT_DATA (seconds);
3903 secs = (int) timeout;
3904 usecs = (int) ((timeout - (double) secs) * 1000000);
3906 else
3907 wrong_type_argument (Qnumberp, seconds);
3909 if (secs < 0 || (secs == 0 && usecs == 0))
3910 secs = -1, usecs = 0;
3912 else
3913 secs = NILP (process) ? -1 : 0;
3915 return
3916 (wait_reading_process_output (secs, usecs, 0, 0,
3917 Qnil,
3918 !NILP (process) ? XPROCESS (process) : NULL,
3919 NILP (just_this_one) ? 0 :
3920 !INTEGERP (just_this_one) ? 1 : -1)
3921 ? Qt : Qnil);
3924 /* Accept a connection for server process SERVER on CHANNEL. */
3926 static int connect_counter = 0;
3928 static void
3929 server_accept_connection (Lisp_Object server, int channel)
3931 Lisp_Object proc, caller, name, buffer;
3932 Lisp_Object contact, host, service;
3933 struct Lisp_Process *ps= XPROCESS (server);
3934 struct Lisp_Process *p;
3935 int s;
3936 union u_sockaddr {
3937 struct sockaddr sa;
3938 struct sockaddr_in in;
3939 #ifdef AF_INET6
3940 struct sockaddr_in6 in6;
3941 #endif
3942 #ifdef HAVE_LOCAL_SOCKETS
3943 struct sockaddr_un un;
3944 #endif
3945 } saddr;
3946 socklen_t len = sizeof saddr;
3948 s = accept (channel, &saddr.sa, &len);
3950 if (s < 0)
3952 int code = errno;
3954 if (code == EAGAIN)
3955 return;
3956 #ifdef EWOULDBLOCK
3957 if (code == EWOULDBLOCK)
3958 return;
3959 #endif
3961 if (!NILP (ps->log))
3962 call3 (ps->log, server, Qnil,
3963 concat3 (build_string ("accept failed with code"),
3964 Fnumber_to_string (make_number (code)),
3965 build_string ("\n")));
3966 return;
3969 connect_counter++;
3971 /* Setup a new process to handle the connection. */
3973 /* Generate a unique identification of the caller, and build contact
3974 information for this process. */
3975 host = Qt;
3976 service = Qnil;
3977 switch (saddr.sa.sa_family)
3979 case AF_INET:
3981 Lisp_Object args[5];
3982 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
3983 args[0] = build_string ("%d.%d.%d.%d");
3984 args[1] = make_number (*ip++);
3985 args[2] = make_number (*ip++);
3986 args[3] = make_number (*ip++);
3987 args[4] = make_number (*ip++);
3988 host = Fformat (5, args);
3989 service = make_number (ntohs (saddr.in.sin_port));
3991 args[0] = build_string (" <%s:%d>");
3992 args[1] = host;
3993 args[2] = service;
3994 caller = Fformat (3, args);
3996 break;
3998 #ifdef AF_INET6
3999 case AF_INET6:
4001 Lisp_Object args[9];
4002 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4003 int i;
4004 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4005 for (i = 0; i < 8; i++)
4006 args[i+1] = make_number (ntohs (ip6[i]));
4007 host = Fformat (9, args);
4008 service = make_number (ntohs (saddr.in.sin_port));
4010 args[0] = build_string (" <[%s]:%d>");
4011 args[1] = host;
4012 args[2] = service;
4013 caller = Fformat (3, args);
4015 break;
4016 #endif
4018 #ifdef HAVE_LOCAL_SOCKETS
4019 case AF_LOCAL:
4020 #endif
4021 default:
4022 caller = Fnumber_to_string (make_number (connect_counter));
4023 caller = concat3 (build_string (" <"), caller, build_string (">"));
4024 break;
4027 /* Create a new buffer name for this process if it doesn't have a
4028 filter. The new buffer name is based on the buffer name or
4029 process name of the server process concatenated with the caller
4030 identification. */
4032 if (!NILP (ps->filter) && !EQ (ps->filter, Qt))
4033 buffer = Qnil;
4034 else
4036 buffer = ps->buffer;
4037 if (!NILP (buffer))
4038 buffer = Fbuffer_name (buffer);
4039 else
4040 buffer = ps->name;
4041 if (!NILP (buffer))
4043 buffer = concat2 (buffer, caller);
4044 buffer = Fget_buffer_create (buffer);
4048 /* Generate a unique name for the new server process. Combine the
4049 server process name with the caller identification. */
4051 name = concat2 (ps->name, caller);
4052 proc = make_process (name);
4054 chan_process[s] = proc;
4056 #ifdef O_NONBLOCK
4057 fcntl (s, F_SETFL, O_NONBLOCK);
4058 #else
4059 #ifdef O_NDELAY
4060 fcntl (s, F_SETFL, O_NDELAY);
4061 #endif
4062 #endif
4064 p = XPROCESS (proc);
4066 /* Build new contact information for this setup. */
4067 contact = Fcopy_sequence (ps->childp);
4068 contact = Fplist_put (contact, QCserver, Qnil);
4069 contact = Fplist_put (contact, QChost, host);
4070 if (!NILP (service))
4071 contact = Fplist_put (contact, QCservice, service);
4072 contact = Fplist_put (contact, QCremote,
4073 conv_sockaddr_to_lisp (&saddr.sa, len));
4074 #ifdef HAVE_GETSOCKNAME
4075 len = sizeof saddr;
4076 if (getsockname (s, &saddr.sa, &len) == 0)
4077 contact = Fplist_put (contact, QClocal,
4078 conv_sockaddr_to_lisp (&saddr.sa, len));
4079 #endif
4081 p->childp = contact;
4082 p->plist = Fcopy_sequence (ps->plist);
4083 p->type = Qnetwork;
4085 p->buffer = buffer;
4086 p->sentinel = ps->sentinel;
4087 p->filter = ps->filter;
4088 p->command = Qnil;
4089 p->pid = 0;
4090 p->infd = s;
4091 p->outfd = s;
4092 p->status = Qrun;
4094 /* Client processes for accepted connections are not stopped initially. */
4095 if (!EQ (p->filter, Qt))
4097 FD_SET (s, &input_wait_mask);
4098 FD_SET (s, &non_keyboard_wait_mask);
4101 if (s > max_process_desc)
4102 max_process_desc = s;
4104 /* Setup coding system for new process based on server process.
4105 This seems to be the proper thing to do, as the coding system
4106 of the new process should reflect the settings at the time the
4107 server socket was opened; not the current settings. */
4109 p->decode_coding_system = ps->decode_coding_system;
4110 p->encode_coding_system = ps->encode_coding_system;
4111 setup_process_coding_systems (proc);
4113 p->decoding_buf = empty_unibyte_string;
4114 p->decoding_carryover = 0;
4115 p->encoding_buf = empty_unibyte_string;
4117 p->inherit_coding_system_flag
4118 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4120 if (!NILP (ps->log))
4121 call3 (ps->log, server, proc,
4122 concat3 (build_string ("accept from "),
4123 (STRINGP (host) ? host : build_string ("-")),
4124 build_string ("\n")));
4126 if (!NILP (p->sentinel))
4127 exec_sentinel (proc,
4128 concat3 (build_string ("open from "),
4129 (STRINGP (host) ? host : build_string ("-")),
4130 build_string ("\n")));
4133 /* This variable is different from waiting_for_input in keyboard.c.
4134 It is used to communicate to a lisp process-filter/sentinel (via the
4135 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4136 for user-input when that process-filter was called.
4137 waiting_for_input cannot be used as that is by definition 0 when
4138 lisp code is being evalled.
4139 This is also used in record_asynch_buffer_change.
4140 For that purpose, this must be 0
4141 when not inside wait_reading_process_output. */
4142 static int waiting_for_user_input_p;
4144 static Lisp_Object
4145 wait_reading_process_output_unwind (Lisp_Object data)
4147 waiting_for_user_input_p = XINT (data);
4148 return Qnil;
4151 /* This is here so breakpoints can be put on it. */
4152 static void
4153 wait_reading_process_output_1 (void)
4157 /* Use a wrapper around select to work around a bug in gdb 5.3.
4158 Normally, the wrapper is optimized away by inlining.
4160 If emacs is stopped inside select, the gdb backtrace doesn't
4161 show the function which called select, so it is practically
4162 impossible to step through wait_reading_process_output. */
4164 #ifndef select
4165 static INLINE int
4166 select_wrapper (int n, fd_set *rfd, fd_set *wfd, fd_set *xfd, struct timeval *tmo)
4168 return select (n, rfd, wfd, xfd, tmo);
4170 #define select select_wrapper
4171 #endif
4173 /* Read and dispose of subprocess output while waiting for timeout to
4174 elapse and/or keyboard input to be available.
4176 TIME_LIMIT is:
4177 timeout in seconds, or
4178 zero for no limit, or
4179 -1 means gobble data immediately available but don't wait for any.
4181 MICROSECS is:
4182 an additional duration to wait, measured in microseconds.
4183 If this is nonzero and time_limit is 0, then the timeout
4184 consists of MICROSECS only.
4186 READ_KBD is a lisp value:
4187 0 to ignore keyboard input, or
4188 1 to return when input is available, or
4189 -1 meaning caller will actually read the input, so don't throw to
4190 the quit handler, or
4192 DO_DISPLAY != 0 means redisplay should be done to show subprocess
4193 output that arrives.
4195 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4196 (and gobble terminal input into the buffer if any arrives).
4198 If WAIT_PROC is specified, wait until something arrives from that
4199 process. The return value is true if we read some input from
4200 that process.
4202 If JUST_WAIT_PROC is non-nil, handle only output from WAIT_PROC
4203 (suspending output from other processes). A negative value
4204 means don't run any timers either.
4206 If WAIT_PROC is specified, then the function returns true if we
4207 received input from that process before the timeout elapsed.
4208 Otherwise, return true if we received input from any process. */
4211 wait_reading_process_output (int time_limit, int microsecs, int read_kbd,
4212 int do_display,
4213 Lisp_Object wait_for_cell,
4214 struct Lisp_Process *wait_proc, int just_wait_proc)
4216 register int channel, nfds;
4217 SELECT_TYPE Available;
4218 SELECT_TYPE Writeok;
4219 int check_write;
4220 int check_delay, no_avail;
4221 int xerrno;
4222 Lisp_Object proc;
4223 EMACS_TIME timeout, end_time;
4224 int wait_channel = -1;
4225 int got_some_input = 0;
4226 int count = SPECPDL_INDEX ();
4228 FD_ZERO (&Available);
4229 FD_ZERO (&Writeok);
4231 if (time_limit == 0 && microsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4232 && !(CONSP (wait_proc->status) && EQ (XCAR (wait_proc->status), Qexit)))
4233 message ("Blocking call to accept-process-output with quit inhibited!!");
4235 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4236 if (wait_proc != NULL)
4237 wait_channel = wait_proc->infd;
4239 record_unwind_protect (wait_reading_process_output_unwind,
4240 make_number (waiting_for_user_input_p));
4241 waiting_for_user_input_p = read_kbd;
4243 /* Since we may need to wait several times,
4244 compute the absolute time to return at. */
4245 if (time_limit || microsecs)
4247 EMACS_GET_TIME (end_time);
4248 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
4249 EMACS_ADD_TIME (end_time, end_time, timeout);
4252 while (1)
4254 int timeout_reduced_for_timers = 0;
4256 /* If calling from keyboard input, do not quit
4257 since we want to return C-g as an input character.
4258 Otherwise, do pending quit if requested. */
4259 if (read_kbd >= 0)
4260 QUIT;
4261 #ifdef SYNC_INPUT
4262 else
4263 process_pending_signals ();
4264 #endif
4266 /* Exit now if the cell we're waiting for became non-nil. */
4267 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4268 break;
4270 /* Compute time from now till when time limit is up */
4271 /* Exit if already run out */
4272 if (time_limit == -1)
4274 /* -1 specified for timeout means
4275 gobble output available now
4276 but don't wait at all. */
4278 EMACS_SET_SECS_USECS (timeout, 0, 0);
4280 else if (time_limit || microsecs)
4282 EMACS_GET_TIME (timeout);
4283 EMACS_SUB_TIME (timeout, end_time, timeout);
4284 if (EMACS_TIME_NEG_P (timeout))
4285 break;
4287 else
4289 EMACS_SET_SECS_USECS (timeout, 100000, 0);
4292 /* Normally we run timers here.
4293 But not if wait_for_cell; in those cases,
4294 the wait is supposed to be short,
4295 and those callers cannot handle running arbitrary Lisp code here. */
4296 if (NILP (wait_for_cell)
4297 && just_wait_proc >= 0)
4299 EMACS_TIME timer_delay;
4303 int old_timers_run = timers_run;
4304 struct buffer *old_buffer = current_buffer;
4305 Lisp_Object old_window = selected_window;
4307 timer_delay = timer_check ();
4309 /* If a timer has run, this might have changed buffers
4310 an alike. Make read_key_sequence aware of that. */
4311 if (timers_run != old_timers_run
4312 && (old_buffer != current_buffer
4313 || !EQ (old_window, selected_window))
4314 && waiting_for_user_input_p == -1)
4315 record_asynch_buffer_change ();
4317 if (timers_run != old_timers_run && do_display)
4318 /* We must retry, since a timer may have requeued itself
4319 and that could alter the time_delay. */
4320 redisplay_preserve_echo_area (9);
4321 else
4322 break;
4324 while (!detect_input_pending ());
4326 /* If there is unread keyboard input, also return. */
4327 if (read_kbd != 0
4328 && requeued_events_pending_p ())
4329 break;
4331 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
4333 EMACS_TIME difference;
4334 EMACS_SUB_TIME (difference, timer_delay, timeout);
4335 if (EMACS_TIME_NEG_P (difference))
4337 timeout = timer_delay;
4338 timeout_reduced_for_timers = 1;
4341 /* If time_limit is -1, we are not going to wait at all. */
4342 else if (time_limit != -1)
4344 /* This is so a breakpoint can be put here. */
4345 wait_reading_process_output_1 ();
4349 /* Cause C-g and alarm signals to take immediate action,
4350 and cause input available signals to zero out timeout.
4352 It is important that we do this before checking for process
4353 activity. If we get a SIGCHLD after the explicit checks for
4354 process activity, timeout is the only way we will know. */
4355 if (read_kbd < 0)
4356 set_waiting_for_input (&timeout);
4358 /* If status of something has changed, and no input is
4359 available, notify the user of the change right away. After
4360 this explicit check, we'll let the SIGCHLD handler zap
4361 timeout to get our attention. */
4362 if (update_tick != process_tick)
4364 SELECT_TYPE Atemp;
4365 SELECT_TYPE Ctemp;
4367 if (kbd_on_hold_p ())
4368 FD_ZERO (&Atemp);
4369 else
4370 Atemp = input_wait_mask;
4371 Ctemp = write_mask;
4373 EMACS_SET_SECS_USECS (timeout, 0, 0);
4374 if ((select (max (max_process_desc, max_input_desc) + 1,
4375 &Atemp,
4376 #ifdef NON_BLOCKING_CONNECT
4377 (num_pending_connects > 0 ? &Ctemp : (SELECT_TYPE *)0),
4378 #else
4379 (SELECT_TYPE *)0,
4380 #endif
4381 (SELECT_TYPE *)0, &timeout)
4382 <= 0))
4384 /* It's okay for us to do this and then continue with
4385 the loop, since timeout has already been zeroed out. */
4386 clear_waiting_for_input ();
4387 status_notify (NULL);
4388 if (do_display) redisplay_preserve_echo_area (13);
4392 /* Don't wait for output from a non-running process. Just
4393 read whatever data has already been received. */
4394 if (wait_proc && wait_proc->raw_status_new)
4395 update_status (wait_proc);
4396 if (wait_proc
4397 && ! EQ (wait_proc->status, Qrun)
4398 && ! EQ (wait_proc->status, Qconnect))
4400 int nread, total_nread = 0;
4402 clear_waiting_for_input ();
4403 XSETPROCESS (proc, wait_proc);
4405 /* Read data from the process, until we exhaust it. */
4406 while (wait_proc->infd >= 0)
4408 nread = read_process_output (proc, wait_proc->infd);
4410 if (nread == 0)
4411 break;
4413 if (0 < nread)
4415 total_nread += nread;
4416 got_some_input = 1;
4418 #ifdef EIO
4419 else if (nread == -1 && EIO == errno)
4420 break;
4421 #endif
4422 #ifdef EAGAIN
4423 else if (nread == -1 && EAGAIN == errno)
4424 break;
4425 #endif
4426 #ifdef EWOULDBLOCK
4427 else if (nread == -1 && EWOULDBLOCK == errno)
4428 break;
4429 #endif
4431 if (total_nread > 0 && do_display)
4432 redisplay_preserve_echo_area (10);
4434 break;
4437 /* Wait till there is something to do */
4439 if (wait_proc && just_wait_proc)
4441 if (wait_proc->infd < 0) /* Terminated */
4442 break;
4443 FD_SET (wait_proc->infd, &Available);
4444 check_delay = 0;
4445 check_write = 0;
4447 else if (!NILP (wait_for_cell))
4449 Available = non_process_wait_mask;
4450 check_delay = 0;
4451 check_write = 0;
4453 else
4455 if (! read_kbd)
4456 Available = non_keyboard_wait_mask;
4457 else
4458 Available = input_wait_mask;
4459 Writeok = write_mask;
4460 #ifdef SELECT_CANT_DO_WRITE_MASK
4461 check_write = 0;
4462 #else
4463 check_write = 1;
4464 #endif
4465 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4468 /* If frame size has changed or the window is newly mapped,
4469 redisplay now, before we start to wait. There is a race
4470 condition here; if a SIGIO arrives between now and the select
4471 and indicates that a frame is trashed, the select may block
4472 displaying a trashed screen. */
4473 if (frame_garbaged && do_display)
4475 clear_waiting_for_input ();
4476 redisplay_preserve_echo_area (11);
4477 if (read_kbd < 0)
4478 set_waiting_for_input (&timeout);
4481 no_avail = 0;
4482 if (read_kbd && detect_input_pending ())
4484 nfds = 0;
4485 no_avail = 1;
4487 else
4490 #ifdef ADAPTIVE_READ_BUFFERING
4491 /* Set the timeout for adaptive read buffering if any
4492 process has non-zero read_output_skip and non-zero
4493 read_output_delay, and we are not reading output for a
4494 specific wait_channel. It is not executed if
4495 Vprocess_adaptive_read_buffering is nil. */
4496 if (process_output_skip && check_delay > 0)
4498 int usecs = EMACS_USECS (timeout);
4499 if (EMACS_SECS (timeout) > 0 || usecs > READ_OUTPUT_DELAY_MAX)
4500 usecs = READ_OUTPUT_DELAY_MAX;
4501 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4503 proc = chan_process[channel];
4504 if (NILP (proc))
4505 continue;
4506 /* Find minimum non-zero read_output_delay among the
4507 processes with non-zero read_output_skip. */
4508 if (XPROCESS (proc)->read_output_delay > 0)
4510 check_delay--;
4511 if (!XPROCESS (proc)->read_output_skip)
4512 continue;
4513 FD_CLR (channel, &Available);
4514 XPROCESS (proc)->read_output_skip = 0;
4515 if (XPROCESS (proc)->read_output_delay < usecs)
4516 usecs = XPROCESS (proc)->read_output_delay;
4519 EMACS_SET_SECS_USECS (timeout, 0, usecs);
4520 process_output_skip = 0;
4522 #endif
4523 #if defined (USE_GTK) || defined (HAVE_GCONF)
4524 nfds = xg_select
4525 #elif defined (HAVE_NS)
4526 nfds = ns_select
4527 #else
4528 nfds = select
4529 #endif
4530 (max (max_process_desc, max_input_desc) + 1,
4531 &Available,
4532 (check_write ? &Writeok : (SELECT_TYPE *)0),
4533 (SELECT_TYPE *)0, &timeout);
4535 #ifdef HAVE_GNUTLS
4536 /* GnuTLS buffers data internally. In lowat mode it leaves
4537 some data in the TCP buffers so that select works, but
4538 with custom pull/push functions we need to check if some
4539 data is available in the buffers manually. */
4540 if (nfds == 0 &&
4541 wait_proc && wait_proc->gnutls_p /* Check for valid process. */
4542 /* Do we have pending data? */
4543 && emacs_gnutls_record_check_pending (wait_proc->gnutls_state) > 0)
4545 nfds = 1;
4546 /* Set to Available. */
4547 FD_SET (wait_proc->infd, &Available);
4549 #endif
4552 xerrno = errno;
4554 /* Make C-g and alarm signals set flags again */
4555 clear_waiting_for_input ();
4557 /* If we woke up due to SIGWINCH, actually change size now. */
4558 do_pending_window_change (0);
4560 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
4561 /* We wanted the full specified time, so return now. */
4562 break;
4563 if (nfds < 0)
4565 if (xerrno == EINTR)
4566 no_avail = 1;
4567 else if (xerrno == EBADF)
4569 #ifdef AIX
4570 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
4571 the child's closure of the pts gives the parent a SIGHUP, and
4572 the ptc file descriptor is automatically closed,
4573 yielding EBADF here or at select() call above.
4574 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
4575 in m/ibmrt-aix.h), and here we just ignore the select error.
4576 Cleanup occurs c/o status_notify after SIGCLD. */
4577 no_avail = 1; /* Cannot depend on values returned */
4578 #else
4579 abort ();
4580 #endif
4582 else
4583 error ("select error: %s", emacs_strerror (xerrno));
4586 if (no_avail)
4588 FD_ZERO (&Available);
4589 check_write = 0;
4592 #if 0 /* When polling is used, interrupt_input is 0,
4593 so get_input_pending should read the input.
4594 So this should not be needed. */
4595 /* If we are using polling for input,
4596 and we see input available, make it get read now.
4597 Otherwise it might not actually get read for a second.
4598 And on hpux, since we turn off polling in wait_reading_process_output,
4599 it might never get read at all if we don't spend much time
4600 outside of wait_reading_process_output. */
4601 if (read_kbd && interrupt_input
4602 && keyboard_bit_set (&Available)
4603 && input_polling_used ())
4604 kill (getpid (), SIGALRM);
4605 #endif
4607 /* Check for keyboard input */
4608 /* If there is any, return immediately
4609 to give it higher priority than subprocesses */
4611 if (read_kbd != 0)
4613 int old_timers_run = timers_run;
4614 struct buffer *old_buffer = current_buffer;
4615 Lisp_Object old_window = selected_window;
4616 int leave = 0;
4618 if (detect_input_pending_run_timers (do_display))
4620 swallow_events (do_display);
4621 if (detect_input_pending_run_timers (do_display))
4622 leave = 1;
4625 /* If a timer has run, this might have changed buffers
4626 an alike. Make read_key_sequence aware of that. */
4627 if (timers_run != old_timers_run
4628 && waiting_for_user_input_p == -1
4629 && (old_buffer != current_buffer
4630 || !EQ (old_window, selected_window)))
4631 record_asynch_buffer_change ();
4633 if (leave)
4634 break;
4637 /* If there is unread keyboard input, also return. */
4638 if (read_kbd != 0
4639 && requeued_events_pending_p ())
4640 break;
4642 /* If we are not checking for keyboard input now,
4643 do process events (but don't run any timers).
4644 This is so that X events will be processed.
4645 Otherwise they may have to wait until polling takes place.
4646 That would causes delays in pasting selections, for example.
4648 (We used to do this only if wait_for_cell.) */
4649 if (read_kbd == 0 && detect_input_pending ())
4651 swallow_events (do_display);
4652 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4653 if (detect_input_pending ())
4654 break;
4655 #endif
4658 /* Exit now if the cell we're waiting for became non-nil. */
4659 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4660 break;
4662 #ifdef SIGIO
4663 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4664 go read it. This can happen with X on BSD after logging out.
4665 In that case, there really is no input and no SIGIO,
4666 but select says there is input. */
4668 if (read_kbd && interrupt_input
4669 && keyboard_bit_set (&Available) && ! noninteractive)
4670 kill (getpid (), SIGIO);
4671 #endif
4673 if (! wait_proc)
4674 got_some_input |= nfds > 0;
4676 /* If checking input just got us a size-change event from X,
4677 obey it now if we should. */
4678 if (read_kbd || ! NILP (wait_for_cell))
4679 do_pending_window_change (0);
4681 /* Check for data from a process. */
4682 if (no_avail || nfds == 0)
4683 continue;
4685 for (channel = 0; channel <= max_input_desc; ++channel)
4687 struct fd_callback_data *d = &fd_callback_info[channel];
4688 if (FD_ISSET (channel, &Available)
4689 && d->func != 0
4690 && (d->condition & FOR_READ) != 0)
4691 d->func (channel, d->data, 1);
4692 if (FD_ISSET (channel, &write_mask)
4693 && d->func != 0
4694 && (d->condition & FOR_WRITE) != 0)
4695 d->func (channel, d->data, 0);
4698 for (channel = 0; channel <= max_process_desc; channel++)
4700 if (FD_ISSET (channel, &Available)
4701 && FD_ISSET (channel, &non_keyboard_wait_mask)
4702 && !FD_ISSET (channel, &non_process_wait_mask))
4704 int nread;
4706 /* If waiting for this channel, arrange to return as
4707 soon as no more input to be processed. No more
4708 waiting. */
4709 if (wait_channel == channel)
4711 wait_channel = -1;
4712 time_limit = -1;
4713 got_some_input = 1;
4715 proc = chan_process[channel];
4716 if (NILP (proc))
4717 continue;
4719 /* If this is a server stream socket, accept connection. */
4720 if (EQ (XPROCESS (proc)->status, Qlisten))
4722 server_accept_connection (proc, channel);
4723 continue;
4726 /* Read data from the process, starting with our
4727 buffered-ahead character if we have one. */
4729 nread = read_process_output (proc, channel);
4730 if (nread > 0)
4732 /* Since read_process_output can run a filter,
4733 which can call accept-process-output,
4734 don't try to read from any other processes
4735 before doing the select again. */
4736 FD_ZERO (&Available);
4738 if (do_display)
4739 redisplay_preserve_echo_area (12);
4741 #ifdef EWOULDBLOCK
4742 else if (nread == -1 && errno == EWOULDBLOCK)
4744 #endif
4745 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
4746 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
4747 #ifdef O_NONBLOCK
4748 else if (nread == -1 && errno == EAGAIN)
4750 #else
4751 #ifdef O_NDELAY
4752 else if (nread == -1 && errno == EAGAIN)
4754 /* Note that we cannot distinguish between no input
4755 available now and a closed pipe.
4756 With luck, a closed pipe will be accompanied by
4757 subprocess termination and SIGCHLD. */
4758 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4760 #endif /* O_NDELAY */
4761 #endif /* O_NONBLOCK */
4762 #ifdef HAVE_PTYS
4763 /* On some OSs with ptys, when the process on one end of
4764 a pty exits, the other end gets an error reading with
4765 errno = EIO instead of getting an EOF (0 bytes read).
4766 Therefore, if we get an error reading and errno =
4767 EIO, just continue, because the child process has
4768 exited and should clean itself up soon (e.g. when we
4769 get a SIGCHLD).
4771 However, it has been known to happen that the SIGCHLD
4772 got lost. So raise the signal again just in case.
4773 It can't hurt. */
4774 else if (nread == -1 && errno == EIO)
4776 /* Clear the descriptor now, so we only raise the
4777 signal once. Don't do this if `process' is only
4778 a pty. */
4779 if (XPROCESS (proc)->pid != -2)
4781 FD_CLR (channel, &input_wait_mask);
4782 FD_CLR (channel, &non_keyboard_wait_mask);
4784 kill (getpid (), SIGCHLD);
4787 #endif /* HAVE_PTYS */
4788 /* If we can detect process termination, don't consider the process
4789 gone just because its pipe is closed. */
4790 #ifdef SIGCHLD
4791 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4793 #endif
4794 else
4796 /* Preserve status of processes already terminated. */
4797 XPROCESS (proc)->tick = ++process_tick;
4798 deactivate_process (proc);
4799 if (XPROCESS (proc)->raw_status_new)
4800 update_status (XPROCESS (proc));
4801 if (EQ (XPROCESS (proc)->status, Qrun))
4802 XPROCESS (proc)->status
4803 = Fcons (Qexit, Fcons (make_number (256), Qnil));
4806 #ifdef NON_BLOCKING_CONNECT
4807 if (FD_ISSET (channel, &Writeok)
4808 && FD_ISSET (channel, &connect_wait_mask))
4810 struct Lisp_Process *p;
4812 FD_CLR (channel, &connect_wait_mask);
4813 FD_CLR (channel, &write_mask);
4814 if (--num_pending_connects < 0)
4815 abort ();
4817 proc = chan_process[channel];
4818 if (NILP (proc))
4819 continue;
4821 p = XPROCESS (proc);
4823 #ifdef GNU_LINUX
4824 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
4825 So only use it on systems where it is known to work. */
4827 socklen_t xlen = sizeof (xerrno);
4828 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
4829 xerrno = errno;
4831 #else
4833 struct sockaddr pname;
4834 int pnamelen = sizeof (pname);
4836 /* If connection failed, getpeername will fail. */
4837 xerrno = 0;
4838 if (getpeername (channel, &pname, &pnamelen) < 0)
4840 /* Obtain connect failure code through error slippage. */
4841 char dummy;
4842 xerrno = errno;
4843 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
4844 xerrno = errno;
4847 #endif
4848 if (xerrno)
4850 p->tick = ++process_tick;
4851 p->status = Fcons (Qfailed, Fcons (make_number (xerrno), Qnil));
4852 deactivate_process (proc);
4854 else
4856 p->status = Qrun;
4857 /* Execute the sentinel here. If we had relied on
4858 status_notify to do it later, it will read input
4859 from the process before calling the sentinel. */
4860 exec_sentinel (proc, build_string ("open\n"));
4861 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
4863 FD_SET (p->infd, &input_wait_mask);
4864 FD_SET (p->infd, &non_keyboard_wait_mask);
4868 #endif /* NON_BLOCKING_CONNECT */
4869 } /* end for each file descriptor */
4870 } /* end while exit conditions not met */
4872 unbind_to (count, Qnil);
4874 /* If calling from keyboard input, do not quit
4875 since we want to return C-g as an input character.
4876 Otherwise, do pending quit if requested. */
4877 if (read_kbd >= 0)
4879 /* Prevent input_pending from remaining set if we quit. */
4880 clear_input_pending ();
4881 QUIT;
4884 return got_some_input;
4887 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
4889 static Lisp_Object
4890 read_process_output_call (Lisp_Object fun_and_args)
4892 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
4895 static Lisp_Object
4896 read_process_output_error_handler (Lisp_Object error_val)
4898 cmd_error_internal (error_val, "error in process filter: ");
4899 Vinhibit_quit = Qt;
4900 update_echo_area ();
4901 Fsleep_for (make_number (2), Qnil);
4902 return Qt;
4905 /* Read pending output from the process channel,
4906 starting with our buffered-ahead character if we have one.
4907 Yield number of decoded characters read.
4909 This function reads at most 4096 characters.
4910 If you want to read all available subprocess output,
4911 you must call it repeatedly until it returns zero.
4913 The characters read are decoded according to PROC's coding-system
4914 for decoding. */
4916 static int
4917 read_process_output (Lisp_Object proc, register int channel)
4919 register ssize_t nbytes;
4920 char *chars;
4921 register Lisp_Object outstream;
4922 register struct Lisp_Process *p = XPROCESS (proc);
4923 register EMACS_INT opoint;
4924 struct coding_system *coding = proc_decode_coding_system[channel];
4925 int carryover = p->decoding_carryover;
4926 int readmax = 4096;
4927 int count = SPECPDL_INDEX ();
4928 Lisp_Object odeactivate;
4930 chars = (char *) alloca (carryover + readmax);
4931 if (carryover)
4932 /* See the comment above. */
4933 memcpy (chars, SDATA (p->decoding_buf), carryover);
4935 #ifdef DATAGRAM_SOCKETS
4936 /* We have a working select, so proc_buffered_char is always -1. */
4937 if (DATAGRAM_CHAN_P (channel))
4939 socklen_t len = datagram_address[channel].len;
4940 nbytes = recvfrom (channel, chars + carryover, readmax,
4941 0, datagram_address[channel].sa, &len);
4943 else
4944 #endif
4946 int buffered = 0 <= proc_buffered_char[channel];
4947 if (buffered)
4949 chars[carryover] = proc_buffered_char[channel];
4950 proc_buffered_char[channel] = -1;
4952 #ifdef HAVE_GNUTLS
4953 if (XPROCESS (proc)->gnutls_p)
4954 nbytes = emacs_gnutls_read (XPROCESS (proc),
4955 chars + carryover + buffered,
4956 readmax - buffered);
4957 else
4958 #endif
4959 nbytes = emacs_read (channel, chars + carryover + buffered,
4960 readmax - buffered);
4961 #ifdef ADAPTIVE_READ_BUFFERING
4962 if (nbytes > 0 && p->adaptive_read_buffering)
4964 int delay = p->read_output_delay;
4965 if (nbytes < 256)
4967 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
4969 if (delay == 0)
4970 process_output_delay_count++;
4971 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
4974 else if (delay > 0 && nbytes == readmax - buffered)
4976 delay -= READ_OUTPUT_DELAY_INCREMENT;
4977 if (delay == 0)
4978 process_output_delay_count--;
4980 p->read_output_delay = delay;
4981 if (delay)
4983 p->read_output_skip = 1;
4984 process_output_skip = 1;
4987 #endif
4988 nbytes += buffered;
4989 nbytes += buffered && nbytes <= 0;
4992 p->decoding_carryover = 0;
4994 /* At this point, NBYTES holds number of bytes just received
4995 (including the one in proc_buffered_char[channel]). */
4996 if (nbytes <= 0)
4998 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
4999 return nbytes;
5000 coding->mode |= CODING_MODE_LAST_BLOCK;
5003 /* Now set NBYTES how many bytes we must decode. */
5004 nbytes += carryover;
5006 odeactivate = Vdeactivate_mark;
5007 /* There's no good reason to let process filters change the current
5008 buffer, and many callers of accept-process-output, sit-for, and
5009 friends don't expect current-buffer to be changed from under them. */
5010 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
5012 /* Read and dispose of the process output. */
5013 outstream = p->filter;
5014 if (!NILP (outstream))
5016 Lisp_Object text;
5017 int outer_running_asynch_code = running_asynch_code;
5018 int waiting = waiting_for_user_input_p;
5020 /* No need to gcpro these, because all we do with them later
5021 is test them for EQness, and none of them should be a string. */
5022 #if 0
5023 Lisp_Object obuffer, okeymap;
5024 XSETBUFFER (obuffer, current_buffer);
5025 okeymap = BVAR (current_buffer, keymap);
5026 #endif
5028 /* We inhibit quit here instead of just catching it so that
5029 hitting ^G when a filter happens to be running won't screw
5030 it up. */
5031 specbind (Qinhibit_quit, Qt);
5032 specbind (Qlast_nonmenu_event, Qt);
5034 /* In case we get recursively called,
5035 and we already saved the match data nonrecursively,
5036 save the same match data in safely recursive fashion. */
5037 if (outer_running_asynch_code)
5039 Lisp_Object tem;
5040 /* Don't clobber the CURRENT match data, either! */
5041 tem = Fmatch_data (Qnil, Qnil, Qnil);
5042 restore_search_regs ();
5043 record_unwind_save_match_data ();
5044 Fset_match_data (tem, Qt);
5047 /* For speed, if a search happens within this code,
5048 save the match data in a special nonrecursive fashion. */
5049 running_asynch_code = 1;
5051 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5052 text = coding->dst_object;
5053 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5054 /* A new coding system might be found. */
5055 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5057 p->decode_coding_system = Vlast_coding_system_used;
5059 /* Don't call setup_coding_system for
5060 proc_decode_coding_system[channel] here. It is done in
5061 detect_coding called via decode_coding above. */
5063 /* If a coding system for encoding is not yet decided, we set
5064 it as the same as coding-system for decoding.
5066 But, before doing that we must check if
5067 proc_encode_coding_system[p->outfd] surely points to a
5068 valid memory because p->outfd will be changed once EOF is
5069 sent to the process. */
5070 if (NILP (p->encode_coding_system)
5071 && proc_encode_coding_system[p->outfd])
5073 p->encode_coding_system
5074 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5075 setup_coding_system (p->encode_coding_system,
5076 proc_encode_coding_system[p->outfd]);
5080 if (coding->carryover_bytes > 0)
5082 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5083 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5084 memcpy (SDATA (p->decoding_buf), coding->carryover,
5085 coding->carryover_bytes);
5086 p->decoding_carryover = coding->carryover_bytes;
5088 if (SBYTES (text) > 0)
5089 internal_condition_case_1 (read_process_output_call,
5090 Fcons (outstream,
5091 Fcons (proc, Fcons (text, Qnil))),
5092 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5093 read_process_output_error_handler);
5095 /* If we saved the match data nonrecursively, restore it now. */
5096 restore_search_regs ();
5097 running_asynch_code = outer_running_asynch_code;
5099 /* Restore waiting_for_user_input_p as it was
5100 when we were called, in case the filter clobbered it. */
5101 waiting_for_user_input_p = waiting;
5103 #if 0 /* Call record_asynch_buffer_change unconditionally,
5104 because we might have changed minor modes or other things
5105 that affect key bindings. */
5106 if (! EQ (Fcurrent_buffer (), obuffer)
5107 || ! EQ (current_buffer->keymap, okeymap))
5108 #endif
5109 /* But do it only if the caller is actually going to read events.
5110 Otherwise there's no need to make him wake up, and it could
5111 cause trouble (for example it would make sit_for return). */
5112 if (waiting_for_user_input_p == -1)
5113 record_asynch_buffer_change ();
5116 /* If no filter, write into buffer if it isn't dead. */
5117 else if (!NILP (p->buffer) && !NILP (BVAR (XBUFFER (p->buffer), name)))
5119 Lisp_Object old_read_only;
5120 EMACS_INT old_begv, old_zv;
5121 EMACS_INT old_begv_byte, old_zv_byte;
5122 EMACS_INT before, before_byte;
5123 EMACS_INT opoint_byte;
5124 Lisp_Object text;
5125 struct buffer *b;
5127 Fset_buffer (p->buffer);
5128 opoint = PT;
5129 opoint_byte = PT_BYTE;
5130 old_read_only = BVAR (current_buffer, read_only);
5131 old_begv = BEGV;
5132 old_zv = ZV;
5133 old_begv_byte = BEGV_BYTE;
5134 old_zv_byte = ZV_BYTE;
5136 BVAR (current_buffer, read_only) = Qnil;
5138 /* Insert new output into buffer
5139 at the current end-of-output marker,
5140 thus preserving logical ordering of input and output. */
5141 if (XMARKER (p->mark)->buffer)
5142 SET_PT_BOTH (clip_to_bounds (BEGV, marker_position (p->mark), ZV),
5143 clip_to_bounds (BEGV_BYTE, marker_byte_position (p->mark),
5144 ZV_BYTE));
5145 else
5146 SET_PT_BOTH (ZV, ZV_BYTE);
5147 before = PT;
5148 before_byte = PT_BYTE;
5150 /* If the output marker is outside of the visible region, save
5151 the restriction and widen. */
5152 if (! (BEGV <= PT && PT <= ZV))
5153 Fwiden ();
5155 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5156 text = coding->dst_object;
5157 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5158 /* A new coding system might be found. See the comment in the
5159 similar code in the previous `if' block. */
5160 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5162 p->decode_coding_system = Vlast_coding_system_used;
5163 if (NILP (p->encode_coding_system)
5164 && proc_encode_coding_system[p->outfd])
5166 p->encode_coding_system
5167 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5168 setup_coding_system (p->encode_coding_system,
5169 proc_encode_coding_system[p->outfd]);
5172 if (coding->carryover_bytes > 0)
5174 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5175 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5176 memcpy (SDATA (p->decoding_buf), coding->carryover,
5177 coding->carryover_bytes);
5178 p->decoding_carryover = coding->carryover_bytes;
5180 /* Adjust the multibyteness of TEXT to that of the buffer. */
5181 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5182 != ! STRING_MULTIBYTE (text))
5183 text = (STRING_MULTIBYTE (text)
5184 ? Fstring_as_unibyte (text)
5185 : Fstring_to_multibyte (text));
5186 /* Insert before markers in case we are inserting where
5187 the buffer's mark is, and the user's next command is Meta-y. */
5188 insert_from_string_before_markers (text, 0, 0,
5189 SCHARS (text), SBYTES (text), 0);
5191 /* Make sure the process marker's position is valid when the
5192 process buffer is changed in the signal_after_change above.
5193 W3 is known to do that. */
5194 if (BUFFERP (p->buffer)
5195 && (b = XBUFFER (p->buffer), b != current_buffer))
5196 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5197 else
5198 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5200 update_mode_lines++;
5202 /* Make sure opoint and the old restrictions
5203 float ahead of any new text just as point would. */
5204 if (opoint >= before)
5206 opoint += PT - before;
5207 opoint_byte += PT_BYTE - before_byte;
5209 if (old_begv > before)
5211 old_begv += PT - before;
5212 old_begv_byte += PT_BYTE - before_byte;
5214 if (old_zv >= before)
5216 old_zv += PT - before;
5217 old_zv_byte += PT_BYTE - before_byte;
5220 /* If the restriction isn't what it should be, set it. */
5221 if (old_begv != BEGV || old_zv != ZV)
5222 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5225 BVAR (current_buffer, read_only) = old_read_only;
5226 SET_PT_BOTH (opoint, opoint_byte);
5228 /* Handling the process output should not deactivate the mark. */
5229 Vdeactivate_mark = odeactivate;
5231 unbind_to (count, Qnil);
5232 return nbytes;
5235 /* Sending data to subprocess */
5237 static jmp_buf send_process_frame;
5238 static Lisp_Object process_sent_to;
5240 #ifndef FORWARD_SIGNAL_TO_MAIN_THREAD
5241 static void send_process_trap (int) NO_RETURN;
5242 #endif
5244 static void
5245 send_process_trap (int ignore)
5247 SIGNAL_THREAD_CHECK (SIGPIPE);
5248 sigunblock (sigmask (SIGPIPE));
5249 longjmp (send_process_frame, 1);
5252 /* Send some data to process PROC.
5253 BUF is the beginning of the data; LEN is the number of characters.
5254 OBJECT is the Lisp object that the data comes from. If OBJECT is
5255 nil or t, it means that the data comes from C string.
5257 If OBJECT is not nil, the data is encoded by PROC's coding-system
5258 for encoding before it is sent.
5260 This function can evaluate Lisp code and can garbage collect. */
5262 static void
5263 send_process (volatile Lisp_Object proc, const char *volatile buf,
5264 volatile EMACS_INT len, volatile Lisp_Object object)
5266 /* Use volatile to protect variables from being clobbered by longjmp. */
5267 struct Lisp_Process *p = XPROCESS (proc);
5268 ssize_t rv;
5269 struct coding_system *coding;
5270 struct gcpro gcpro1;
5271 void (*volatile old_sigpipe) (int);
5273 GCPRO1 (object);
5275 if (p->raw_status_new)
5276 update_status (p);
5277 if (! EQ (p->status, Qrun))
5278 error ("Process %s not running", SDATA (p->name));
5279 if (p->outfd < 0)
5280 error ("Output file descriptor of %s is closed", SDATA (p->name));
5282 coding = proc_encode_coding_system[p->outfd];
5283 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5285 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5286 || (BUFFERP (object)
5287 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5288 || EQ (object, Qt))
5290 p->encode_coding_system
5291 = complement_process_encoding_system (p->encode_coding_system);
5292 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5294 /* The coding system for encoding was changed to raw-text
5295 because we sent a unibyte text previously. Now we are
5296 sending a multibyte text, thus we must encode it by the
5297 original coding system specified for the current process.
5299 Another reason we comming here is that the coding system
5300 was just complemented and new one was returned by
5301 complement_process_encoding_system. */
5302 setup_coding_system (p->encode_coding_system, coding);
5303 Vlast_coding_system_used = p->encode_coding_system;
5305 coding->src_multibyte = 1;
5307 else
5309 /* For sending a unibyte text, character code conversion should
5310 not take place but EOL conversion should. So, setup raw-text
5311 or one of the subsidiary if we have not yet done it. */
5312 if (CODING_REQUIRE_ENCODING (coding))
5314 if (CODING_REQUIRE_FLUSHING (coding))
5316 /* But, before changing the coding, we must flush out data. */
5317 coding->mode |= CODING_MODE_LAST_BLOCK;
5318 send_process (proc, "", 0, Qt);
5319 coding->mode &= CODING_MODE_LAST_BLOCK;
5321 setup_coding_system (raw_text_coding_system
5322 (Vlast_coding_system_used),
5323 coding);
5324 coding->src_multibyte = 0;
5327 coding->dst_multibyte = 0;
5329 if (CODING_REQUIRE_ENCODING (coding))
5331 coding->dst_object = Qt;
5332 if (BUFFERP (object))
5334 EMACS_INT from_byte, from, to;
5335 EMACS_INT save_pt, save_pt_byte;
5336 struct buffer *cur = current_buffer;
5338 set_buffer_internal (XBUFFER (object));
5339 save_pt = PT, save_pt_byte = PT_BYTE;
5341 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5342 from = BYTE_TO_CHAR (from_byte);
5343 to = BYTE_TO_CHAR (from_byte + len);
5344 TEMP_SET_PT_BOTH (from, from_byte);
5345 encode_coding_object (coding, object, from, from_byte,
5346 to, from_byte + len, Qt);
5347 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5348 set_buffer_internal (cur);
5350 else if (STRINGP (object))
5352 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5353 SBYTES (object), Qt);
5355 else
5357 coding->dst_object = make_unibyte_string (buf, len);
5358 coding->produced = len;
5361 len = coding->produced;
5362 object = coding->dst_object;
5363 buf = SSDATA (object);
5366 if (pty_max_bytes == 0)
5368 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
5369 pty_max_bytes = fpathconf (p->outfd, _PC_MAX_CANON);
5370 if (pty_max_bytes < 0)
5371 pty_max_bytes = 250;
5372 #else
5373 pty_max_bytes = 250;
5374 #endif
5375 /* Deduct one, to leave space for the eof. */
5376 pty_max_bytes--;
5379 /* 2000-09-21: Emacs 20.7, sparc-sun-solaris-2.6, GCC 2.95.2,
5380 CFLAGS="-g -O": The value of the parameter `proc' is clobbered
5381 when returning with longjmp despite being declared volatile. */
5382 if (!setjmp (send_process_frame))
5384 p = XPROCESS (proc); /* Repair any setjmp clobbering. */
5386 process_sent_to = proc;
5387 while (len > 0)
5389 EMACS_INT this = len;
5391 /* Send this batch, using one or more write calls. */
5392 while (this > 0)
5394 EMACS_INT written = 0;
5395 int outfd = p->outfd;
5396 old_sigpipe = (void (*) (int)) signal (SIGPIPE, send_process_trap);
5397 #ifdef DATAGRAM_SOCKETS
5398 if (DATAGRAM_CHAN_P (outfd))
5400 rv = sendto (outfd, buf, this,
5401 0, datagram_address[outfd].sa,
5402 datagram_address[outfd].len);
5403 if (0 <= rv)
5404 written = rv;
5405 else if (errno == EMSGSIZE)
5407 signal (SIGPIPE, old_sigpipe);
5408 report_file_error ("sending datagram",
5409 Fcons (proc, Qnil));
5412 else
5413 #endif
5415 #ifdef HAVE_GNUTLS
5416 if (XPROCESS (proc)->gnutls_p)
5417 written = emacs_gnutls_write (XPROCESS (proc),
5418 buf, this);
5419 else
5420 #endif
5421 written = emacs_write (outfd, buf, this);
5422 rv = (written ? 0 : -1);
5423 #ifdef ADAPTIVE_READ_BUFFERING
5424 if (p->read_output_delay > 0
5425 && p->adaptive_read_buffering == 1)
5427 p->read_output_delay = 0;
5428 process_output_delay_count--;
5429 p->read_output_skip = 0;
5431 #endif
5433 signal (SIGPIPE, old_sigpipe);
5435 if (rv < 0)
5437 if (0
5438 #ifdef EWOULDBLOCK
5439 || errno == EWOULDBLOCK
5440 #endif
5441 #ifdef EAGAIN
5442 || errno == EAGAIN
5443 #endif
5445 /* Buffer is full. Wait, accepting input;
5446 that may allow the program
5447 to finish doing output and read more. */
5449 EMACS_INT offset = 0;
5451 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5452 /* A gross hack to work around a bug in FreeBSD.
5453 In the following sequence, read(2) returns
5454 bogus data:
5456 write(2) 1022 bytes
5457 write(2) 954 bytes, get EAGAIN
5458 read(2) 1024 bytes in process_read_output
5459 read(2) 11 bytes in process_read_output
5461 That is, read(2) returns more bytes than have
5462 ever been written successfully. The 1033 bytes
5463 read are the 1022 bytes written successfully
5464 after processing (for example with CRs added if
5465 the terminal is set up that way which it is
5466 here). The same bytes will be seen again in a
5467 later read(2), without the CRs. */
5469 if (errno == EAGAIN)
5471 int flags = FWRITE;
5472 ioctl (p->outfd, TIOCFLUSH, &flags);
5474 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5476 /* Running filters might relocate buffers or strings.
5477 Arrange to relocate BUF. */
5478 if (BUFFERP (object))
5479 offset = BUF_PTR_BYTE_POS (XBUFFER (object),
5480 (unsigned char *) buf);
5481 else if (STRINGP (object))
5482 offset = buf - SSDATA (object);
5484 #ifdef EMACS_HAS_USECS
5485 wait_reading_process_output (0, 20000, 0, 0, Qnil, NULL, 0);
5486 #else
5487 wait_reading_process_output (1, 0, 0, 0, Qnil, NULL, 0);
5488 #endif
5490 if (BUFFERP (object))
5491 buf = (char *) BUF_BYTE_ADDRESS (XBUFFER (object),
5492 offset);
5493 else if (STRINGP (object))
5494 buf = offset + SSDATA (object);
5496 else
5497 /* This is a real error. */
5498 report_file_error ("writing to process", Fcons (proc, Qnil));
5500 buf += written;
5501 len -= written;
5502 this -= written;
5506 else
5508 signal (SIGPIPE, old_sigpipe);
5509 proc = process_sent_to;
5510 p = XPROCESS (proc);
5511 p->raw_status_new = 0;
5512 p->status = Fcons (Qexit, Fcons (make_number (256), Qnil));
5513 p->tick = ++process_tick;
5514 deactivate_process (proc);
5515 error ("SIGPIPE raised on process %s; closed it", SDATA (p->name));
5518 UNGCPRO;
5521 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5522 3, 3, 0,
5523 doc: /* Send current contents of region as input to PROCESS.
5524 PROCESS may be a process, a buffer, the name of a process or buffer, or
5525 nil, indicating the current buffer's process.
5526 Called from program, takes three arguments, PROCESS, START and END.
5527 If the region is more than 500 characters long,
5528 it is sent in several bunches. This may happen even for shorter regions.
5529 Output from processes can arrive in between bunches. */)
5530 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5532 Lisp_Object proc;
5533 EMACS_INT start1, end1;
5535 proc = get_process (process);
5536 validate_region (&start, &end);
5538 if (XINT (start) < GPT && XINT (end) > GPT)
5539 move_gap (XINT (start));
5541 start1 = CHAR_TO_BYTE (XINT (start));
5542 end1 = CHAR_TO_BYTE (XINT (end));
5543 send_process (proc, (char *) BYTE_POS_ADDR (start1), end1 - start1,
5544 Fcurrent_buffer ());
5546 return Qnil;
5549 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5550 2, 2, 0,
5551 doc: /* Send PROCESS the contents of STRING as input.
5552 PROCESS may be a process, a buffer, the name of a process or buffer, or
5553 nil, indicating the current buffer's process.
5554 If STRING is more than 500 characters long,
5555 it is sent in several bunches. This may happen even for shorter strings.
5556 Output from processes can arrive in between bunches. */)
5557 (Lisp_Object process, Lisp_Object string)
5559 Lisp_Object proc;
5560 CHECK_STRING (string);
5561 proc = get_process (process);
5562 send_process (proc, SSDATA (string),
5563 SBYTES (string), string);
5564 return Qnil;
5567 /* Return the foreground process group for the tty/pty that
5568 the process P uses. */
5569 static int
5570 emacs_get_tty_pgrp (struct Lisp_Process *p)
5572 int gid = -1;
5574 #ifdef TIOCGPGRP
5575 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5577 int fd;
5578 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5579 master side. Try the slave side. */
5580 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
5582 if (fd != -1)
5584 ioctl (fd, TIOCGPGRP, &gid);
5585 emacs_close (fd);
5588 #endif /* defined (TIOCGPGRP ) */
5590 return gid;
5593 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5594 Sprocess_running_child_p, 0, 1, 0,
5595 doc: /* Return t if PROCESS has given the terminal to a child.
5596 If the operating system does not make it possible to find out,
5597 return t unconditionally. */)
5598 (Lisp_Object process)
5600 /* Initialize in case ioctl doesn't exist or gives an error,
5601 in a way that will cause returning t. */
5602 int gid;
5603 Lisp_Object proc;
5604 struct Lisp_Process *p;
5606 proc = get_process (process);
5607 p = XPROCESS (proc);
5609 if (!EQ (p->type, Qreal))
5610 error ("Process %s is not a subprocess",
5611 SDATA (p->name));
5612 if (p->infd < 0)
5613 error ("Process %s is not active",
5614 SDATA (p->name));
5616 gid = emacs_get_tty_pgrp (p);
5618 if (gid == p->pid)
5619 return Qnil;
5620 return Qt;
5623 /* send a signal number SIGNO to PROCESS.
5624 If CURRENT_GROUP is t, that means send to the process group
5625 that currently owns the terminal being used to communicate with PROCESS.
5626 This is used for various commands in shell mode.
5627 If CURRENT_GROUP is lambda, that means send to the process group
5628 that currently owns the terminal, but only if it is NOT the shell itself.
5630 If NOMSG is zero, insert signal-announcements into process's buffers
5631 right away.
5633 If we can, we try to signal PROCESS by sending control characters
5634 down the pty. This allows us to signal inferiors who have changed
5635 their uid, for which killpg would return an EPERM error. */
5637 static void
5638 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5639 int nomsg)
5641 Lisp_Object proc;
5642 register struct Lisp_Process *p;
5643 int gid;
5644 int no_pgrp = 0;
5646 proc = get_process (process);
5647 p = XPROCESS (proc);
5649 if (!EQ (p->type, Qreal))
5650 error ("Process %s is not a subprocess",
5651 SDATA (p->name));
5652 if (p->infd < 0)
5653 error ("Process %s is not active",
5654 SDATA (p->name));
5656 if (!p->pty_flag)
5657 current_group = Qnil;
5659 /* If we are using pgrps, get a pgrp number and make it negative. */
5660 if (NILP (current_group))
5661 /* Send the signal to the shell's process group. */
5662 gid = p->pid;
5663 else
5665 #ifdef SIGNALS_VIA_CHARACTERS
5666 /* If possible, send signals to the entire pgrp
5667 by sending an input character to it. */
5669 struct termios t;
5670 cc_t *sig_char = NULL;
5672 tcgetattr (p->infd, &t);
5674 switch (signo)
5676 case SIGINT:
5677 sig_char = &t.c_cc[VINTR];
5678 break;
5680 case SIGQUIT:
5681 sig_char = &t.c_cc[VQUIT];
5682 break;
5684 case SIGTSTP:
5685 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5686 sig_char = &t.c_cc[VSWTCH];
5687 #else
5688 sig_char = &t.c_cc[VSUSP];
5689 #endif
5690 break;
5693 if (sig_char && *sig_char != CDISABLE)
5695 send_process (proc, (char *) sig_char, 1, Qnil);
5696 return;
5698 /* If we can't send the signal with a character,
5699 fall through and send it another way. */
5701 /* The code above may fall through if it can't
5702 handle the signal. */
5703 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5705 #ifdef TIOCGPGRP
5706 /* Get the current pgrp using the tty itself, if we have that.
5707 Otherwise, use the pty to get the pgrp.
5708 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5709 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5710 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5711 His patch indicates that if TIOCGPGRP returns an error, then
5712 we should just assume that p->pid is also the process group id. */
5714 gid = emacs_get_tty_pgrp (p);
5716 if (gid == -1)
5717 /* If we can't get the information, assume
5718 the shell owns the tty. */
5719 gid = p->pid;
5721 /* It is not clear whether anything really can set GID to -1.
5722 Perhaps on some system one of those ioctls can or could do so.
5723 Or perhaps this is vestigial. */
5724 if (gid == -1)
5725 no_pgrp = 1;
5726 #else /* ! defined (TIOCGPGRP ) */
5727 /* Can't select pgrps on this system, so we know that
5728 the child itself heads the pgrp. */
5729 gid = p->pid;
5730 #endif /* ! defined (TIOCGPGRP ) */
5732 /* If current_group is lambda, and the shell owns the terminal,
5733 don't send any signal. */
5734 if (EQ (current_group, Qlambda) && gid == p->pid)
5735 return;
5738 switch (signo)
5740 #ifdef SIGCONT
5741 case SIGCONT:
5742 p->raw_status_new = 0;
5743 p->status = Qrun;
5744 p->tick = ++process_tick;
5745 if (!nomsg)
5747 status_notify (NULL);
5748 redisplay_preserve_echo_area (13);
5750 break;
5751 #endif /* ! defined (SIGCONT) */
5752 case SIGINT:
5753 case SIGQUIT:
5754 case SIGKILL:
5755 flush_pending_output (p->infd);
5756 break;
5759 /* If we don't have process groups, send the signal to the immediate
5760 subprocess. That isn't really right, but it's better than any
5761 obvious alternative. */
5762 if (no_pgrp)
5764 kill (p->pid, signo);
5765 return;
5768 /* gid may be a pid, or minus a pgrp's number */
5769 #ifdef TIOCSIGSEND
5770 if (!NILP (current_group))
5772 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
5773 EMACS_KILLPG (gid, signo);
5775 else
5777 gid = - p->pid;
5778 kill (gid, signo);
5780 #else /* ! defined (TIOCSIGSEND) */
5781 EMACS_KILLPG (gid, signo);
5782 #endif /* ! defined (TIOCSIGSEND) */
5785 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
5786 doc: /* Interrupt process PROCESS.
5787 PROCESS may be a process, a buffer, or the name of a process or buffer.
5788 No arg or nil means current buffer's process.
5789 Second arg CURRENT-GROUP non-nil means send signal to
5790 the current process-group of the process's controlling terminal
5791 rather than to the process's own process group.
5792 If the process is a shell, this means interrupt current subjob
5793 rather than the shell.
5795 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
5796 don't send the signal. */)
5797 (Lisp_Object process, Lisp_Object current_group)
5799 process_send_signal (process, SIGINT, current_group, 0);
5800 return process;
5803 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
5804 doc: /* Kill process PROCESS. May be process or name of one.
5805 See function `interrupt-process' for more details on usage. */)
5806 (Lisp_Object process, Lisp_Object current_group)
5808 process_send_signal (process, SIGKILL, current_group, 0);
5809 return process;
5812 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
5813 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
5814 See function `interrupt-process' for more details on usage. */)
5815 (Lisp_Object process, Lisp_Object current_group)
5817 process_send_signal (process, SIGQUIT, current_group, 0);
5818 return process;
5821 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
5822 doc: /* Stop process PROCESS. May be process or name of one.
5823 See function `interrupt-process' for more details on usage.
5824 If PROCESS is a network or serial process, inhibit handling of incoming
5825 traffic. */)
5826 (Lisp_Object process, Lisp_Object current_group)
5828 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5830 struct Lisp_Process *p;
5832 p = XPROCESS (process);
5833 if (NILP (p->command)
5834 && p->infd >= 0)
5836 FD_CLR (p->infd, &input_wait_mask);
5837 FD_CLR (p->infd, &non_keyboard_wait_mask);
5839 p->command = Qt;
5840 return process;
5842 #ifndef SIGTSTP
5843 error ("No SIGTSTP support");
5844 #else
5845 process_send_signal (process, SIGTSTP, current_group, 0);
5846 #endif
5847 return process;
5850 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
5851 doc: /* Continue process PROCESS. May be process or name of one.
5852 See function `interrupt-process' for more details on usage.
5853 If PROCESS is a network or serial process, resume handling of incoming
5854 traffic. */)
5855 (Lisp_Object process, Lisp_Object current_group)
5857 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5859 struct Lisp_Process *p;
5861 p = XPROCESS (process);
5862 if (EQ (p->command, Qt)
5863 && p->infd >= 0
5864 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
5866 FD_SET (p->infd, &input_wait_mask);
5867 FD_SET (p->infd, &non_keyboard_wait_mask);
5868 #ifdef WINDOWSNT
5869 if (fd_info[ p->infd ].flags & FILE_SERIAL)
5870 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
5871 #else /* not WINDOWSNT */
5872 tcflush (p->infd, TCIFLUSH);
5873 #endif /* not WINDOWSNT */
5875 p->command = Qnil;
5876 return process;
5878 #ifdef SIGCONT
5879 process_send_signal (process, SIGCONT, current_group, 0);
5880 #else
5881 error ("No SIGCONT support");
5882 #endif
5883 return process;
5886 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
5887 2, 2, "sProcess (name or number): \nnSignal code: ",
5888 doc: /* Send PROCESS the signal with code SIGCODE.
5889 PROCESS may also be a number specifying the process id of the
5890 process to signal; in this case, the process need not be a child of
5891 this Emacs.
5892 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
5893 (Lisp_Object process, Lisp_Object sigcode)
5895 pid_t pid;
5897 if (INTEGERP (process))
5899 pid = XINT (process);
5900 goto got_it;
5903 if (FLOATP (process))
5905 pid = (pid_t) XFLOAT_DATA (process);
5906 goto got_it;
5909 if (STRINGP (process))
5911 Lisp_Object tem;
5912 if (tem = Fget_process (process), NILP (tem))
5914 pid = XINT (Fstring_to_number (process, make_number (10)));
5915 if (pid > 0)
5916 goto got_it;
5918 process = tem;
5920 else
5921 process = get_process (process);
5923 if (NILP (process))
5924 return process;
5926 CHECK_PROCESS (process);
5927 pid = XPROCESS (process)->pid;
5928 if (pid <= 0)
5929 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
5931 got_it:
5933 #define parse_signal(NAME, VALUE) \
5934 else if (!xstrcasecmp (name, NAME)) \
5935 XSETINT (sigcode, VALUE)
5937 if (INTEGERP (sigcode))
5939 else
5941 char *name;
5943 CHECK_SYMBOL (sigcode);
5944 name = SSDATA (SYMBOL_NAME (sigcode));
5946 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
5947 name += 3;
5949 if (0)
5951 #ifdef SIGUSR1
5952 parse_signal ("usr1", SIGUSR1);
5953 #endif
5954 #ifdef SIGUSR2
5955 parse_signal ("usr2", SIGUSR2);
5956 #endif
5957 #ifdef SIGTERM
5958 parse_signal ("term", SIGTERM);
5959 #endif
5960 #ifdef SIGHUP
5961 parse_signal ("hup", SIGHUP);
5962 #endif
5963 #ifdef SIGINT
5964 parse_signal ("int", SIGINT);
5965 #endif
5966 #ifdef SIGQUIT
5967 parse_signal ("quit", SIGQUIT);
5968 #endif
5969 #ifdef SIGILL
5970 parse_signal ("ill", SIGILL);
5971 #endif
5972 #ifdef SIGABRT
5973 parse_signal ("abrt", SIGABRT);
5974 #endif
5975 #ifdef SIGEMT
5976 parse_signal ("emt", SIGEMT);
5977 #endif
5978 #ifdef SIGKILL
5979 parse_signal ("kill", SIGKILL);
5980 #endif
5981 #ifdef SIGFPE
5982 parse_signal ("fpe", SIGFPE);
5983 #endif
5984 #ifdef SIGBUS
5985 parse_signal ("bus", SIGBUS);
5986 #endif
5987 #ifdef SIGSEGV
5988 parse_signal ("segv", SIGSEGV);
5989 #endif
5990 #ifdef SIGSYS
5991 parse_signal ("sys", SIGSYS);
5992 #endif
5993 #ifdef SIGPIPE
5994 parse_signal ("pipe", SIGPIPE);
5995 #endif
5996 #ifdef SIGALRM
5997 parse_signal ("alrm", SIGALRM);
5998 #endif
5999 #ifdef SIGURG
6000 parse_signal ("urg", SIGURG);
6001 #endif
6002 #ifdef SIGSTOP
6003 parse_signal ("stop", SIGSTOP);
6004 #endif
6005 #ifdef SIGTSTP
6006 parse_signal ("tstp", SIGTSTP);
6007 #endif
6008 #ifdef SIGCONT
6009 parse_signal ("cont", SIGCONT);
6010 #endif
6011 #ifdef SIGCHLD
6012 parse_signal ("chld", SIGCHLD);
6013 #endif
6014 #ifdef SIGTTIN
6015 parse_signal ("ttin", SIGTTIN);
6016 #endif
6017 #ifdef SIGTTOU
6018 parse_signal ("ttou", SIGTTOU);
6019 #endif
6020 #ifdef SIGIO
6021 parse_signal ("io", SIGIO);
6022 #endif
6023 #ifdef SIGXCPU
6024 parse_signal ("xcpu", SIGXCPU);
6025 #endif
6026 #ifdef SIGXFSZ
6027 parse_signal ("xfsz", SIGXFSZ);
6028 #endif
6029 #ifdef SIGVTALRM
6030 parse_signal ("vtalrm", SIGVTALRM);
6031 #endif
6032 #ifdef SIGPROF
6033 parse_signal ("prof", SIGPROF);
6034 #endif
6035 #ifdef SIGWINCH
6036 parse_signal ("winch", SIGWINCH);
6037 #endif
6038 #ifdef SIGINFO
6039 parse_signal ("info", SIGINFO);
6040 #endif
6041 else
6042 error ("Undefined signal name %s", name);
6045 #undef parse_signal
6047 return make_number (kill (pid, XINT (sigcode)));
6050 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6051 doc: /* Make PROCESS see end-of-file in its input.
6052 EOF comes after any text already sent to it.
6053 PROCESS may be a process, a buffer, the name of a process or buffer, or
6054 nil, indicating the current buffer's process.
6055 If PROCESS is a network connection, or is a process communicating
6056 through a pipe (as opposed to a pty), then you cannot send any more
6057 text to PROCESS after you call this function.
6058 If PROCESS is a serial process, wait until all output written to the
6059 process has been transmitted to the serial port. */)
6060 (Lisp_Object process)
6062 Lisp_Object proc;
6063 struct coding_system *coding;
6065 if (DATAGRAM_CONN_P (process))
6066 return process;
6068 proc = get_process (process);
6069 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
6071 /* Make sure the process is really alive. */
6072 if (XPROCESS (proc)->raw_status_new)
6073 update_status (XPROCESS (proc));
6074 if (! EQ (XPROCESS (proc)->status, Qrun))
6075 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6077 if (CODING_REQUIRE_FLUSHING (coding))
6079 coding->mode |= CODING_MODE_LAST_BLOCK;
6080 send_process (proc, "", 0, Qnil);
6083 if (XPROCESS (proc)->pty_flag)
6084 send_process (proc, "\004", 1, Qnil);
6085 else if (EQ (XPROCESS (proc)->type, Qserial))
6087 #ifndef WINDOWSNT
6088 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6089 error ("tcdrain() failed: %s", emacs_strerror (errno));
6090 #endif /* not WINDOWSNT */
6091 /* Do nothing on Windows because writes are blocking. */
6093 else
6095 int old_outfd, new_outfd;
6097 #ifdef HAVE_SHUTDOWN
6098 /* If this is a network connection, or socketpair is used
6099 for communication with the subprocess, call shutdown to cause EOF.
6100 (In some old system, shutdown to socketpair doesn't work.
6101 Then we just can't win.) */
6102 if (EQ (XPROCESS (proc)->type, Qnetwork)
6103 || XPROCESS (proc)->outfd == XPROCESS (proc)->infd)
6104 shutdown (XPROCESS (proc)->outfd, 1);
6105 /* In case of socketpair, outfd == infd, so don't close it. */
6106 if (XPROCESS (proc)->outfd != XPROCESS (proc)->infd)
6107 emacs_close (XPROCESS (proc)->outfd);
6108 #else /* not HAVE_SHUTDOWN */
6109 emacs_close (XPROCESS (proc)->outfd);
6110 #endif /* not HAVE_SHUTDOWN */
6111 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6112 if (new_outfd < 0)
6113 abort ();
6114 old_outfd = XPROCESS (proc)->outfd;
6116 if (!proc_encode_coding_system[new_outfd])
6117 proc_encode_coding_system[new_outfd]
6118 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
6119 memcpy (proc_encode_coding_system[new_outfd],
6120 proc_encode_coding_system[old_outfd],
6121 sizeof (struct coding_system));
6122 memset (proc_encode_coding_system[old_outfd], 0,
6123 sizeof (struct coding_system));
6125 XPROCESS (proc)->outfd = new_outfd;
6127 return process;
6130 /* On receipt of a signal that a child status has changed, loop asking
6131 about children with changed statuses until the system says there
6132 are no more.
6134 All we do is change the status; we do not run sentinels or print
6135 notifications. That is saved for the next time keyboard input is
6136 done, in order to avoid timing errors.
6138 ** WARNING: this can be called during garbage collection.
6139 Therefore, it must not be fooled by the presence of mark bits in
6140 Lisp objects.
6142 ** USG WARNING: Although it is not obvious from the documentation
6143 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6144 signal() before executing at least one wait(), otherwise the
6145 handler will be called again, resulting in an infinite loop. The
6146 relevant portion of the documentation reads "SIGCLD signals will be
6147 queued and the signal-catching function will be continually
6148 reentered until the queue is empty". Invoking signal() causes the
6149 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6150 Inc.
6152 ** Malloc WARNING: This should never call malloc either directly or
6153 indirectly; if it does, that is a bug */
6155 #ifdef SIGCHLD
6156 static void
6157 sigchld_handler (int signo)
6159 int old_errno = errno;
6160 Lisp_Object proc;
6161 struct Lisp_Process *p;
6163 SIGNAL_THREAD_CHECK (signo);
6165 while (1)
6167 pid_t pid;
6168 int w;
6169 Lisp_Object tail;
6171 #ifdef WNOHANG
6172 #ifndef WUNTRACED
6173 #define WUNTRACED 0
6174 #endif /* no WUNTRACED */
6175 /* Keep trying to get a status until we get a definitive result. */
6178 errno = 0;
6179 pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
6181 while (pid < 0 && errno == EINTR);
6183 if (pid <= 0)
6185 /* PID == 0 means no processes found, PID == -1 means a real
6186 failure. We have done all our job, so return. */
6188 errno = old_errno;
6189 return;
6191 #else
6192 pid = wait (&w);
6193 #endif /* no WNOHANG */
6195 /* Find the process that signaled us, and record its status. */
6197 /* The process can have been deleted by Fdelete_process. */
6198 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6200 Lisp_Object xpid = XCAR (tail);
6201 if ((INTEGERP (xpid) && pid == (pid_t) XINT (xpid))
6202 || (FLOATP (xpid) && pid == (pid_t) XFLOAT_DATA (xpid)))
6204 XSETCAR (tail, Qnil);
6205 goto sigchld_end_of_loop;
6209 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6210 p = 0;
6211 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6213 proc = XCDR (XCAR (tail));
6214 p = XPROCESS (proc);
6215 if (EQ (p->type, Qreal) && p->pid == pid)
6216 break;
6217 p = 0;
6220 /* Look for an asynchronous process whose pid hasn't been filled
6221 in yet. */
6222 if (p == 0)
6223 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6225 proc = XCDR (XCAR (tail));
6226 p = XPROCESS (proc);
6227 if (p->pid == -1)
6228 break;
6229 p = 0;
6232 /* Change the status of the process that was found. */
6233 if (p != 0)
6235 int clear_desc_flag = 0;
6237 p->tick = ++process_tick;
6238 p->raw_status = w;
6239 p->raw_status_new = 1;
6241 /* If process has terminated, stop waiting for its output. */
6242 if ((WIFSIGNALED (w) || WIFEXITED (w))
6243 && p->infd >= 0)
6244 clear_desc_flag = 1;
6246 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
6247 if (clear_desc_flag)
6249 FD_CLR (p->infd, &input_wait_mask);
6250 FD_CLR (p->infd, &non_keyboard_wait_mask);
6253 /* Tell wait_reading_process_output that it needs to wake up and
6254 look around. */
6255 if (input_available_clear_time)
6256 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6259 /* There was no asynchronous process found for that pid: we have
6260 a synchronous process. */
6261 else
6263 synch_process_alive = 0;
6265 /* Report the status of the synchronous process. */
6266 if (WIFEXITED (w))
6267 synch_process_retcode = WRETCODE (w);
6268 else if (WIFSIGNALED (w))
6269 synch_process_termsig = WTERMSIG (w);
6271 /* Tell wait_reading_process_output that it needs to wake up and
6272 look around. */
6273 if (input_available_clear_time)
6274 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6277 sigchld_end_of_loop:
6280 /* On some systems, we must return right away.
6281 If any more processes want to signal us, we will
6282 get another signal.
6283 Otherwise (on systems that have WNOHANG), loop around
6284 to use up all the processes that have something to tell us. */
6285 #if (defined WINDOWSNT \
6286 || (defined USG && !defined GNU_LINUX \
6287 && !(defined HPUX && defined WNOHANG)))
6288 errno = old_errno;
6289 return;
6290 #endif /* USG, but not HPUX with WNOHANG */
6293 #endif /* SIGCHLD */
6296 static Lisp_Object
6297 exec_sentinel_unwind (Lisp_Object data)
6299 XPROCESS (XCAR (data))->sentinel = XCDR (data);
6300 return Qnil;
6303 static Lisp_Object
6304 exec_sentinel_error_handler (Lisp_Object error_val)
6306 cmd_error_internal (error_val, "error in process sentinel: ");
6307 Vinhibit_quit = Qt;
6308 update_echo_area ();
6309 Fsleep_for (make_number (2), Qnil);
6310 return Qt;
6313 static void
6314 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6316 Lisp_Object sentinel, odeactivate;
6317 register struct Lisp_Process *p = XPROCESS (proc);
6318 int count = SPECPDL_INDEX ();
6319 int outer_running_asynch_code = running_asynch_code;
6320 int waiting = waiting_for_user_input_p;
6322 if (inhibit_sentinels)
6323 return;
6325 /* No need to gcpro these, because all we do with them later
6326 is test them for EQness, and none of them should be a string. */
6327 odeactivate = Vdeactivate_mark;
6328 #if 0
6329 Lisp_Object obuffer, okeymap;
6330 XSETBUFFER (obuffer, current_buffer);
6331 okeymap = BVAR (current_buffer, keymap);
6332 #endif
6334 /* There's no good reason to let sentinels change the current
6335 buffer, and many callers of accept-process-output, sit-for, and
6336 friends don't expect current-buffer to be changed from under them. */
6337 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
6339 sentinel = p->sentinel;
6340 if (NILP (sentinel))
6341 return;
6343 /* Zilch the sentinel while it's running, to avoid recursive invocations;
6344 assure that it gets restored no matter how the sentinel exits. */
6345 p->sentinel = Qnil;
6346 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
6347 /* Inhibit quit so that random quits don't screw up a running filter. */
6348 specbind (Qinhibit_quit, Qt);
6349 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6351 /* In case we get recursively called,
6352 and we already saved the match data nonrecursively,
6353 save the same match data in safely recursive fashion. */
6354 if (outer_running_asynch_code)
6356 Lisp_Object tem;
6357 tem = Fmatch_data (Qnil, Qnil, Qnil);
6358 restore_search_regs ();
6359 record_unwind_save_match_data ();
6360 Fset_match_data (tem, Qt);
6363 /* For speed, if a search happens within this code,
6364 save the match data in a special nonrecursive fashion. */
6365 running_asynch_code = 1;
6367 internal_condition_case_1 (read_process_output_call,
6368 Fcons (sentinel,
6369 Fcons (proc, Fcons (reason, Qnil))),
6370 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6371 exec_sentinel_error_handler);
6373 /* If we saved the match data nonrecursively, restore it now. */
6374 restore_search_regs ();
6375 running_asynch_code = outer_running_asynch_code;
6377 Vdeactivate_mark = odeactivate;
6379 /* Restore waiting_for_user_input_p as it was
6380 when we were called, in case the filter clobbered it. */
6381 waiting_for_user_input_p = waiting;
6383 #if 0
6384 if (! EQ (Fcurrent_buffer (), obuffer)
6385 || ! EQ (current_buffer->keymap, okeymap))
6386 #endif
6387 /* But do it only if the caller is actually going to read events.
6388 Otherwise there's no need to make him wake up, and it could
6389 cause trouble (for example it would make sit_for return). */
6390 if (waiting_for_user_input_p == -1)
6391 record_asynch_buffer_change ();
6393 unbind_to (count, Qnil);
6396 /* Report all recent events of a change in process status
6397 (either run the sentinel or output a message).
6398 This is usually done while Emacs is waiting for keyboard input
6399 but can be done at other times. */
6401 static void
6402 status_notify (struct Lisp_Process *deleting_process)
6404 register Lisp_Object proc, buffer;
6405 Lisp_Object tail, msg;
6406 struct gcpro gcpro1, gcpro2;
6408 tail = Qnil;
6409 msg = Qnil;
6410 /* We need to gcpro tail; if read_process_output calls a filter
6411 which deletes a process and removes the cons to which tail points
6412 from Vprocess_alist, and then causes a GC, tail is an unprotected
6413 reference. */
6414 GCPRO2 (tail, msg);
6416 /* Set this now, so that if new processes are created by sentinels
6417 that we run, we get called again to handle their status changes. */
6418 update_tick = process_tick;
6420 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6422 Lisp_Object symbol;
6423 register struct Lisp_Process *p;
6425 proc = Fcdr (XCAR (tail));
6426 p = XPROCESS (proc);
6428 if (p->tick != p->update_tick)
6430 p->update_tick = p->tick;
6432 /* If process is still active, read any output that remains. */
6433 while (! EQ (p->filter, Qt)
6434 && ! EQ (p->status, Qconnect)
6435 && ! EQ (p->status, Qlisten)
6436 /* Network or serial process not stopped: */
6437 && ! EQ (p->command, Qt)
6438 && p->infd >= 0
6439 && p != deleting_process
6440 && read_process_output (proc, p->infd) > 0);
6442 buffer = p->buffer;
6444 /* Get the text to use for the message. */
6445 if (p->raw_status_new)
6446 update_status (p);
6447 msg = status_message (p);
6449 /* If process is terminated, deactivate it or delete it. */
6450 symbol = p->status;
6451 if (CONSP (p->status))
6452 symbol = XCAR (p->status);
6454 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6455 || EQ (symbol, Qclosed))
6457 if (delete_exited_processes)
6458 remove_process (proc);
6459 else
6460 deactivate_process (proc);
6463 /* The actions above may have further incremented p->tick.
6464 So set p->update_tick again
6465 so that an error in the sentinel will not cause
6466 this code to be run again. */
6467 p->update_tick = p->tick;
6468 /* Now output the message suitably. */
6469 if (!NILP (p->sentinel))
6470 exec_sentinel (proc, msg);
6471 /* Don't bother with a message in the buffer
6472 when a process becomes runnable. */
6473 else if (!EQ (symbol, Qrun) && !NILP (buffer))
6475 Lisp_Object tem;
6476 struct buffer *old = current_buffer;
6477 EMACS_INT opoint, opoint_byte;
6478 EMACS_INT before, before_byte;
6480 /* Avoid error if buffer is deleted
6481 (probably that's why the process is dead, too) */
6482 if (NILP (BVAR (XBUFFER (buffer), name)))
6483 continue;
6484 Fset_buffer (buffer);
6486 opoint = PT;
6487 opoint_byte = PT_BYTE;
6488 /* Insert new output into buffer
6489 at the current end-of-output marker,
6490 thus preserving logical ordering of input and output. */
6491 if (XMARKER (p->mark)->buffer)
6492 Fgoto_char (p->mark);
6493 else
6494 SET_PT_BOTH (ZV, ZV_BYTE);
6496 before = PT;
6497 before_byte = PT_BYTE;
6499 tem = BVAR (current_buffer, read_only);
6500 BVAR (current_buffer, read_only) = Qnil;
6501 insert_string ("\nProcess ");
6502 Finsert (1, &p->name);
6503 insert_string (" ");
6504 Finsert (1, &msg);
6505 BVAR (current_buffer, read_only) = tem;
6506 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6508 if (opoint >= before)
6509 SET_PT_BOTH (opoint + (PT - before),
6510 opoint_byte + (PT_BYTE - before_byte));
6511 else
6512 SET_PT_BOTH (opoint, opoint_byte);
6514 set_buffer_internal (old);
6517 } /* end for */
6519 update_mode_lines++; /* in case buffers use %s in mode-line-format */
6520 UNGCPRO;
6524 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6525 Sset_process_coding_system, 1, 3, 0,
6526 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6527 DECODING will be used to decode subprocess output and ENCODING to
6528 encode subprocess input. */)
6529 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6531 register struct Lisp_Process *p;
6533 CHECK_PROCESS (process);
6534 p = XPROCESS (process);
6535 if (p->infd < 0)
6536 error ("Input file descriptor of %s closed", SDATA (p->name));
6537 if (p->outfd < 0)
6538 error ("Output file descriptor of %s closed", SDATA (p->name));
6539 Fcheck_coding_system (decoding);
6540 Fcheck_coding_system (encoding);
6541 encoding = coding_inherit_eol_type (encoding, Qnil);
6542 p->decode_coding_system = decoding;
6543 p->encode_coding_system = encoding;
6544 setup_process_coding_systems (process);
6546 return Qnil;
6549 DEFUN ("process-coding-system",
6550 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6551 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6552 (register Lisp_Object process)
6554 CHECK_PROCESS (process);
6555 return Fcons (XPROCESS (process)->decode_coding_system,
6556 XPROCESS (process)->encode_coding_system);
6559 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6560 Sset_process_filter_multibyte, 2, 2, 0,
6561 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6562 If FLAG is non-nil, the filter is given multibyte strings.
6563 If FLAG is nil, the filter is given unibyte strings. In this case,
6564 all character code conversion except for end-of-line conversion is
6565 suppressed. */)
6566 (Lisp_Object process, Lisp_Object flag)
6568 register struct Lisp_Process *p;
6570 CHECK_PROCESS (process);
6571 p = XPROCESS (process);
6572 if (NILP (flag))
6573 p->decode_coding_system = raw_text_coding_system (p->decode_coding_system);
6574 setup_process_coding_systems (process);
6576 return Qnil;
6579 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6580 Sprocess_filter_multibyte_p, 1, 1, 0,
6581 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6582 (Lisp_Object process)
6584 register struct Lisp_Process *p;
6585 struct coding_system *coding;
6587 CHECK_PROCESS (process);
6588 p = XPROCESS (process);
6589 coding = proc_decode_coding_system[p->infd];
6590 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6596 void
6597 add_gpm_wait_descriptor (int desc)
6599 add_keyboard_wait_descriptor (desc);
6602 void
6603 delete_gpm_wait_descriptor (int desc)
6605 delete_keyboard_wait_descriptor (desc);
6608 # ifdef SIGIO
6610 /* Return nonzero if *MASK has a bit set
6611 that corresponds to one of the keyboard input descriptors. */
6613 static int
6614 keyboard_bit_set (fd_set *mask)
6616 int fd;
6618 for (fd = 0; fd <= max_input_desc; fd++)
6619 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6620 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6621 return 1;
6623 return 0;
6625 # endif
6627 #else /* not subprocesses */
6629 /* Defined on msdos.c. */
6630 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
6631 EMACS_TIME *);
6633 /* Implementation of wait_reading_process_output, assuming that there
6634 are no subprocesses. Used only by the MS-DOS build.
6636 Wait for timeout to elapse and/or keyboard input to be available.
6638 time_limit is:
6639 timeout in seconds, or
6640 zero for no limit, or
6641 -1 means gobble data immediately available but don't wait for any.
6643 read_kbd is a Lisp_Object:
6644 0 to ignore keyboard input, or
6645 1 to return when input is available, or
6646 -1 means caller will actually read the input, so don't throw to
6647 the quit handler.
6649 see full version for other parameters. We know that wait_proc will
6650 always be NULL, since `subprocesses' isn't defined.
6652 do_display != 0 means redisplay should be done to show subprocess
6653 output that arrives.
6655 Return true if we received input from any process. */
6658 wait_reading_process_output (int time_limit, int microsecs, int read_kbd,
6659 int do_display,
6660 Lisp_Object wait_for_cell,
6661 struct Lisp_Process *wait_proc, int just_wait_proc)
6663 register int nfds;
6664 EMACS_TIME end_time, timeout;
6665 SELECT_TYPE waitchannels;
6666 int xerrno;
6668 /* What does time_limit really mean? */
6669 if (time_limit || microsecs)
6671 EMACS_GET_TIME (end_time);
6672 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
6673 EMACS_ADD_TIME (end_time, end_time, timeout);
6676 /* Turn off periodic alarms (in case they are in use)
6677 and then turn off any other atimers,
6678 because the select emulator uses alarms. */
6679 stop_polling ();
6680 turn_on_atimers (0);
6682 while (1)
6684 int timeout_reduced_for_timers = 0;
6686 /* If calling from keyboard input, do not quit
6687 since we want to return C-g as an input character.
6688 Otherwise, do pending quit if requested. */
6689 if (read_kbd >= 0)
6690 QUIT;
6692 /* Exit now if the cell we're waiting for became non-nil. */
6693 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6694 break;
6696 /* Compute time from now till when time limit is up */
6697 /* Exit if already run out */
6698 if (time_limit == -1)
6700 /* -1 specified for timeout means
6701 gobble output available now
6702 but don't wait at all. */
6704 EMACS_SET_SECS_USECS (timeout, 0, 0);
6706 else if (time_limit || microsecs)
6708 EMACS_GET_TIME (timeout);
6709 EMACS_SUB_TIME (timeout, end_time, timeout);
6710 if (EMACS_TIME_NEG_P (timeout))
6711 break;
6713 else
6715 EMACS_SET_SECS_USECS (timeout, 100000, 0);
6718 /* If our caller will not immediately handle keyboard events,
6719 run timer events directly.
6720 (Callers that will immediately read keyboard events
6721 call timer_delay on their own.) */
6722 if (NILP (wait_for_cell))
6724 EMACS_TIME timer_delay;
6728 int old_timers_run = timers_run;
6729 timer_delay = timer_check ();
6730 if (timers_run != old_timers_run && do_display)
6731 /* We must retry, since a timer may have requeued itself
6732 and that could alter the time delay. */
6733 redisplay_preserve_echo_area (14);
6734 else
6735 break;
6737 while (!detect_input_pending ());
6739 /* If there is unread keyboard input, also return. */
6740 if (read_kbd != 0
6741 && requeued_events_pending_p ())
6742 break;
6744 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
6746 EMACS_TIME difference;
6747 EMACS_SUB_TIME (difference, timer_delay, timeout);
6748 if (EMACS_TIME_NEG_P (difference))
6750 timeout = timer_delay;
6751 timeout_reduced_for_timers = 1;
6756 /* Cause C-g and alarm signals to take immediate action,
6757 and cause input available signals to zero out timeout. */
6758 if (read_kbd < 0)
6759 set_waiting_for_input (&timeout);
6761 /* Wait till there is something to do. */
6763 if (! read_kbd && NILP (wait_for_cell))
6764 FD_ZERO (&waitchannels);
6765 else
6766 FD_SET (0, &waitchannels);
6768 /* If a frame has been newly mapped and needs updating,
6769 reprocess its display stuff. */
6770 if (frame_garbaged && do_display)
6772 clear_waiting_for_input ();
6773 redisplay_preserve_echo_area (15);
6774 if (read_kbd < 0)
6775 set_waiting_for_input (&timeout);
6778 if (read_kbd && detect_input_pending ())
6780 nfds = 0;
6781 FD_ZERO (&waitchannels);
6783 else
6784 nfds = select (1, &waitchannels, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
6785 &timeout);
6787 xerrno = errno;
6789 /* Make C-g and alarm signals set flags again */
6790 clear_waiting_for_input ();
6792 /* If we woke up due to SIGWINCH, actually change size now. */
6793 do_pending_window_change (0);
6795 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
6796 /* We waited the full specified time, so return now. */
6797 break;
6799 if (nfds == -1)
6801 /* If the system call was interrupted, then go around the
6802 loop again. */
6803 if (xerrno == EINTR)
6804 FD_ZERO (&waitchannels);
6805 else
6806 error ("select error: %s", emacs_strerror (xerrno));
6809 /* Check for keyboard input */
6811 if (read_kbd
6812 && detect_input_pending_run_timers (do_display))
6814 swallow_events (do_display);
6815 if (detect_input_pending_run_timers (do_display))
6816 break;
6819 /* If there is unread keyboard input, also return. */
6820 if (read_kbd
6821 && requeued_events_pending_p ())
6822 break;
6824 /* If wait_for_cell. check for keyboard input
6825 but don't run any timers.
6826 ??? (It seems wrong to me to check for keyboard
6827 input at all when wait_for_cell, but the code
6828 has been this way since July 1994.
6829 Try changing this after version 19.31.) */
6830 if (! NILP (wait_for_cell)
6831 && detect_input_pending ())
6833 swallow_events (do_display);
6834 if (detect_input_pending ())
6835 break;
6838 /* Exit now if the cell we're waiting for became non-nil. */
6839 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6840 break;
6843 start_polling ();
6845 return 0;
6848 #endif /* not subprocesses */
6850 /* The following functions are needed even if async subprocesses are
6851 not supported. Some of them are no-op stubs in that case. */
6853 /* Add DESC to the set of keyboard input descriptors. */
6855 void
6856 add_keyboard_wait_descriptor (int desc)
6858 #ifdef subprocesses /* actually means "not MSDOS" */
6859 FD_SET (desc, &input_wait_mask);
6860 FD_SET (desc, &non_process_wait_mask);
6861 if (desc > max_input_desc)
6862 max_input_desc = desc;
6863 #endif
6866 /* From now on, do not expect DESC to give keyboard input. */
6868 void
6869 delete_keyboard_wait_descriptor (int desc)
6871 #ifdef subprocesses
6872 int fd;
6873 int lim = max_input_desc;
6875 FD_CLR (desc, &input_wait_mask);
6876 FD_CLR (desc, &non_process_wait_mask);
6878 if (desc == max_input_desc)
6879 for (fd = 0; fd < lim; fd++)
6880 if (FD_ISSET (fd, &input_wait_mask) || FD_ISSET (fd, &write_mask))
6881 max_input_desc = fd;
6882 #endif
6885 /* Setup coding systems of PROCESS. */
6887 void
6888 setup_process_coding_systems (Lisp_Object process)
6890 #ifdef subprocesses
6891 struct Lisp_Process *p = XPROCESS (process);
6892 int inch = p->infd;
6893 int outch = p->outfd;
6894 Lisp_Object coding_system;
6896 if (inch < 0 || outch < 0)
6897 return;
6899 if (!proc_decode_coding_system[inch])
6900 proc_decode_coding_system[inch]
6901 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
6902 coding_system = p->decode_coding_system;
6903 if (! NILP (p->filter))
6905 else if (BUFFERP (p->buffer))
6907 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
6908 coding_system = raw_text_coding_system (coding_system);
6910 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
6912 if (!proc_encode_coding_system[outch])
6913 proc_encode_coding_system[outch]
6914 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
6915 setup_coding_system (p->encode_coding_system,
6916 proc_encode_coding_system[outch]);
6917 #endif
6920 /* Close all descriptors currently in use for communication
6921 with subprocess. This is used in a newly-forked subprocess
6922 to get rid of irrelevant descriptors. */
6924 void
6925 close_process_descs (void)
6927 #ifndef DOS_NT
6928 int i;
6929 for (i = 0; i < MAXDESC; i++)
6931 Lisp_Object process;
6932 process = chan_process[i];
6933 if (!NILP (process))
6935 int in = XPROCESS (process)->infd;
6936 int out = XPROCESS (process)->outfd;
6937 if (in >= 0)
6938 emacs_close (in);
6939 if (out >= 0 && in != out)
6940 emacs_close (out);
6943 #endif
6946 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
6947 doc: /* Return the (or a) process associated with BUFFER.
6948 BUFFER may be a buffer or the name of one. */)
6949 (register Lisp_Object buffer)
6951 #ifdef subprocesses
6952 register Lisp_Object buf, tail, proc;
6954 if (NILP (buffer)) return Qnil;
6955 buf = Fget_buffer (buffer);
6956 if (NILP (buf)) return Qnil;
6958 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6960 proc = Fcdr (XCAR (tail));
6961 if (PROCESSP (proc) && EQ (XPROCESS (proc)->buffer, buf))
6962 return proc;
6964 #endif /* subprocesses */
6965 return Qnil;
6968 DEFUN ("process-inherit-coding-system-flag",
6969 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
6970 1, 1, 0,
6971 doc: /* Return the value of inherit-coding-system flag for PROCESS.
6972 If this flag is t, `buffer-file-coding-system' of the buffer
6973 associated with PROCESS will inherit the coding system used to decode
6974 the process output. */)
6975 (register Lisp_Object process)
6977 #ifdef subprocesses
6978 CHECK_PROCESS (process);
6979 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
6980 #else
6981 /* Ignore the argument and return the value of
6982 inherit-process-coding-system. */
6983 return inherit_process_coding_system ? Qt : Qnil;
6984 #endif
6987 /* Kill all processes associated with `buffer'.
6988 If `buffer' is nil, kill all processes */
6990 void
6991 kill_buffer_processes (Lisp_Object buffer)
6993 #ifdef subprocesses
6994 Lisp_Object tail, proc;
6996 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6998 proc = XCDR (XCAR (tail));
6999 if (PROCESSP (proc)
7000 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
7002 if (NETCONN_P (proc) || SERIALCONN_P (proc))
7003 Fdelete_process (proc);
7004 else if (XPROCESS (proc)->infd >= 0)
7005 process_send_signal (proc, SIGHUP, Qnil, 1);
7008 #else /* subprocesses */
7009 /* Since we have no subprocesses, this does nothing. */
7010 #endif /* subprocesses */
7013 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
7014 Swaiting_for_user_input_p, 0, 0, 0,
7015 doc: /* Returns non-nil if Emacs is waiting for input from the user.
7016 This is intended for use by asynchronous process output filters and sentinels. */)
7017 (void)
7019 #ifdef subprocesses
7020 return (waiting_for_user_input_p ? Qt : Qnil);
7021 #else
7022 return Qnil;
7023 #endif
7026 /* Stop reading input from keyboard sources. */
7028 void
7029 hold_keyboard_input (void)
7031 kbd_is_on_hold = 1;
7034 /* Resume reading input from keyboard sources. */
7036 void
7037 unhold_keyboard_input (void)
7039 kbd_is_on_hold = 0;
7042 /* Return non-zero if keyboard input is on hold, zero otherwise. */
7045 kbd_on_hold_p (void)
7047 return kbd_is_on_hold;
7051 /* Enumeration of and access to system processes a-la ps(1). */
7053 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7054 0, 0, 0,
7055 doc: /* Return a list of numerical process IDs of all running processes.
7056 If this functionality is unsupported, return nil.
7058 See `process-attributes' for getting attributes of a process given its ID. */)
7059 (void)
7061 return list_system_processes ();
7064 DEFUN ("process-attributes", Fprocess_attributes,
7065 Sprocess_attributes, 1, 1, 0,
7066 doc: /* Return attributes of the process given by its PID, a number.
7068 Value is an alist where each element is a cons cell of the form
7070 \(KEY . VALUE)
7072 If this functionality is unsupported, the value is nil.
7074 See `list-system-processes' for getting a list of all process IDs.
7076 The KEYs of the attributes that this function may return are listed
7077 below, together with the type of the associated VALUE (in parentheses).
7078 Not all platforms support all of these attributes; unsupported
7079 attributes will not appear in the returned alist.
7080 Unless explicitly indicated otherwise, numbers can have either
7081 integer or floating point values.
7083 euid -- Effective user User ID of the process (number)
7084 user -- User name corresponding to euid (string)
7085 egid -- Effective user Group ID of the process (number)
7086 group -- Group name corresponding to egid (string)
7087 comm -- Command name (executable name only) (string)
7088 state -- Process state code, such as "S", "R", or "T" (string)
7089 ppid -- Parent process ID (number)
7090 pgrp -- Process group ID (number)
7091 sess -- Session ID, i.e. process ID of session leader (number)
7092 ttname -- Controlling tty name (string)
7093 tpgid -- ID of foreground process group on the process's tty (number)
7094 minflt -- number of minor page faults (number)
7095 majflt -- number of major page faults (number)
7096 cminflt -- cumulative number of minor page faults (number)
7097 cmajflt -- cumulative number of major page faults (number)
7098 utime -- user time used by the process, in the (HIGH LOW USEC) format
7099 stime -- system time used by the process, in the (HIGH LOW USEC) format
7100 time -- sum of utime and stime, in the (HIGH LOW USEC) format
7101 cutime -- user time used by the process and its children, (HIGH LOW USEC)
7102 cstime -- system time used by the process and its children, (HIGH LOW USEC)
7103 ctime -- sum of cutime and cstime, in the (HIGH LOW USEC) format
7104 pri -- priority of the process (number)
7105 nice -- nice value of the process (number)
7106 thcount -- process thread count (number)
7107 start -- time the process started, in the (HIGH LOW USEC) format
7108 vsize -- virtual memory size of the process in KB's (number)
7109 rss -- resident set size of the process in KB's (number)
7110 etime -- elapsed time the process is running, in (HIGH LOW USEC) format
7111 pcpu -- percents of CPU time used by the process (floating-point number)
7112 pmem -- percents of total physical memory used by process's resident set
7113 (floating-point number)
7114 args -- command line which invoked the process (string). */)
7115 ( Lisp_Object pid)
7117 return system_process_attributes (pid);
7121 void
7122 init_process (void)
7124 #ifdef subprocesses
7125 register int i;
7127 inhibit_sentinels = 0;
7129 #ifdef SIGCHLD
7130 #ifndef CANNOT_DUMP
7131 if (! noninteractive || initialized)
7132 #endif
7133 signal (SIGCHLD, sigchld_handler);
7134 #endif
7136 FD_ZERO (&input_wait_mask);
7137 FD_ZERO (&non_keyboard_wait_mask);
7138 FD_ZERO (&non_process_wait_mask);
7139 FD_ZERO (&write_mask);
7140 max_process_desc = 0;
7141 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7143 #ifdef NON_BLOCKING_CONNECT
7144 FD_ZERO (&connect_wait_mask);
7145 num_pending_connects = 0;
7146 #endif
7148 #ifdef ADAPTIVE_READ_BUFFERING
7149 process_output_delay_count = 0;
7150 process_output_skip = 0;
7151 #endif
7153 /* Don't do this, it caused infinite select loops. The display
7154 method should call add_keyboard_wait_descriptor on stdin if it
7155 needs that. */
7156 #if 0
7157 FD_SET (0, &input_wait_mask);
7158 #endif
7160 Vprocess_alist = Qnil;
7161 #ifdef SIGCHLD
7162 deleted_pid_list = Qnil;
7163 #endif
7164 for (i = 0; i < MAXDESC; i++)
7166 chan_process[i] = Qnil;
7167 proc_buffered_char[i] = -1;
7169 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7170 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7171 #ifdef DATAGRAM_SOCKETS
7172 memset (datagram_address, 0, sizeof datagram_address);
7173 #endif
7176 Lisp_Object subfeatures = Qnil;
7177 const struct socket_options *sopt;
7179 #define ADD_SUBFEATURE(key, val) \
7180 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7182 #ifdef NON_BLOCKING_CONNECT
7183 ADD_SUBFEATURE (QCnowait, Qt);
7184 #endif
7185 #ifdef DATAGRAM_SOCKETS
7186 ADD_SUBFEATURE (QCtype, Qdatagram);
7187 #endif
7188 #ifdef HAVE_SEQPACKET
7189 ADD_SUBFEATURE (QCtype, Qseqpacket);
7190 #endif
7191 #ifdef HAVE_LOCAL_SOCKETS
7192 ADD_SUBFEATURE (QCfamily, Qlocal);
7193 #endif
7194 ADD_SUBFEATURE (QCfamily, Qipv4);
7195 #ifdef AF_INET6
7196 ADD_SUBFEATURE (QCfamily, Qipv6);
7197 #endif
7198 #ifdef HAVE_GETSOCKNAME
7199 ADD_SUBFEATURE (QCservice, Qt);
7200 #endif
7201 #if defined(O_NONBLOCK) || defined(O_NDELAY)
7202 ADD_SUBFEATURE (QCserver, Qt);
7203 #endif
7205 for (sopt = socket_options; sopt->name; sopt++)
7206 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7208 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7211 #if defined (DARWIN_OS)
7212 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7213 processes. As such, we only change the default value. */
7214 if (initialized)
7216 char const *release = (STRINGP (Voperating_system_release)
7217 ? SSDATA (Voperating_system_release)
7218 : 0);
7219 if (!release || !release[0] || (release[0] < MIN_PTY_KERNEL_VERSION
7220 && release[1] == '.')) {
7221 Vprocess_connection_type = Qnil;
7224 #endif
7225 #endif /* subprocesses */
7226 kbd_is_on_hold = 0;
7229 void
7230 syms_of_process (void)
7232 #ifdef subprocesses
7234 Qprocessp = intern_c_string ("processp");
7235 staticpro (&Qprocessp);
7236 Qrun = intern_c_string ("run");
7237 staticpro (&Qrun);
7238 Qstop = intern_c_string ("stop");
7239 staticpro (&Qstop);
7240 Qsignal = intern_c_string ("signal");
7241 staticpro (&Qsignal);
7243 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7244 here again.
7246 Qexit = intern_c_string ("exit");
7247 staticpro (&Qexit); */
7249 Qopen = intern_c_string ("open");
7250 staticpro (&Qopen);
7251 Qclosed = intern_c_string ("closed");
7252 staticpro (&Qclosed);
7253 Qconnect = intern_c_string ("connect");
7254 staticpro (&Qconnect);
7255 Qfailed = intern_c_string ("failed");
7256 staticpro (&Qfailed);
7257 Qlisten = intern_c_string ("listen");
7258 staticpro (&Qlisten);
7259 Qlocal = intern_c_string ("local");
7260 staticpro (&Qlocal);
7261 Qipv4 = intern_c_string ("ipv4");
7262 staticpro (&Qipv4);
7263 #ifdef AF_INET6
7264 Qipv6 = intern_c_string ("ipv6");
7265 staticpro (&Qipv6);
7266 #endif
7267 Qdatagram = intern_c_string ("datagram");
7268 staticpro (&Qdatagram);
7269 Qseqpacket = intern_c_string ("seqpacket");
7270 staticpro (&Qseqpacket);
7272 QCport = intern_c_string (":port");
7273 staticpro (&QCport);
7274 QCspeed = intern_c_string (":speed");
7275 staticpro (&QCspeed);
7276 QCprocess = intern_c_string (":process");
7277 staticpro (&QCprocess);
7279 QCbytesize = intern_c_string (":bytesize");
7280 staticpro (&QCbytesize);
7281 QCstopbits = intern_c_string (":stopbits");
7282 staticpro (&QCstopbits);
7283 QCparity = intern_c_string (":parity");
7284 staticpro (&QCparity);
7285 Qodd = intern_c_string ("odd");
7286 staticpro (&Qodd);
7287 Qeven = intern_c_string ("even");
7288 staticpro (&Qeven);
7289 QCflowcontrol = intern_c_string (":flowcontrol");
7290 staticpro (&QCflowcontrol);
7291 Qhw = intern_c_string ("hw");
7292 staticpro (&Qhw);
7293 Qsw = intern_c_string ("sw");
7294 staticpro (&Qsw);
7295 QCsummary = intern_c_string (":summary");
7296 staticpro (&QCsummary);
7298 Qreal = intern_c_string ("real");
7299 staticpro (&Qreal);
7300 Qnetwork = intern_c_string ("network");
7301 staticpro (&Qnetwork);
7302 Qserial = intern_c_string ("serial");
7303 staticpro (&Qserial);
7304 QCbuffer = intern_c_string (":buffer");
7305 staticpro (&QCbuffer);
7306 QChost = intern_c_string (":host");
7307 staticpro (&QChost);
7308 QCservice = intern_c_string (":service");
7309 staticpro (&QCservice);
7310 QClocal = intern_c_string (":local");
7311 staticpro (&QClocal);
7312 QCremote = intern_c_string (":remote");
7313 staticpro (&QCremote);
7314 QCcoding = intern_c_string (":coding");
7315 staticpro (&QCcoding);
7316 QCserver = intern_c_string (":server");
7317 staticpro (&QCserver);
7318 QCnowait = intern_c_string (":nowait");
7319 staticpro (&QCnowait);
7320 QCsentinel = intern_c_string (":sentinel");
7321 staticpro (&QCsentinel);
7322 QClog = intern_c_string (":log");
7323 staticpro (&QClog);
7324 QCnoquery = intern_c_string (":noquery");
7325 staticpro (&QCnoquery);
7326 QCstop = intern_c_string (":stop");
7327 staticpro (&QCstop);
7328 QCoptions = intern_c_string (":options");
7329 staticpro (&QCoptions);
7330 QCplist = intern_c_string (":plist");
7331 staticpro (&QCplist);
7333 Qlast_nonmenu_event = intern_c_string ("last-nonmenu-event");
7334 staticpro (&Qlast_nonmenu_event);
7336 staticpro (&Vprocess_alist);
7337 #ifdef SIGCHLD
7338 staticpro (&deleted_pid_list);
7339 #endif
7341 #endif /* subprocesses */
7343 QCname = intern_c_string (":name");
7344 staticpro (&QCname);
7345 QCtype = intern_c_string (":type");
7346 staticpro (&QCtype);
7348 Qeuid = intern_c_string ("euid");
7349 staticpro (&Qeuid);
7350 Qegid = intern_c_string ("egid");
7351 staticpro (&Qegid);
7352 Quser = intern_c_string ("user");
7353 staticpro (&Quser);
7354 Qgroup = intern_c_string ("group");
7355 staticpro (&Qgroup);
7356 Qcomm = intern_c_string ("comm");
7357 staticpro (&Qcomm);
7358 Qstate = intern_c_string ("state");
7359 staticpro (&Qstate);
7360 Qppid = intern_c_string ("ppid");
7361 staticpro (&Qppid);
7362 Qpgrp = intern_c_string ("pgrp");
7363 staticpro (&Qpgrp);
7364 Qsess = intern_c_string ("sess");
7365 staticpro (&Qsess);
7366 Qttname = intern_c_string ("ttname");
7367 staticpro (&Qttname);
7368 Qtpgid = intern_c_string ("tpgid");
7369 staticpro (&Qtpgid);
7370 Qminflt = intern_c_string ("minflt");
7371 staticpro (&Qminflt);
7372 Qmajflt = intern_c_string ("majflt");
7373 staticpro (&Qmajflt);
7374 Qcminflt = intern_c_string ("cminflt");
7375 staticpro (&Qcminflt);
7376 Qcmajflt = intern_c_string ("cmajflt");
7377 staticpro (&Qcmajflt);
7378 Qutime = intern_c_string ("utime");
7379 staticpro (&Qutime);
7380 Qstime = intern_c_string ("stime");
7381 staticpro (&Qstime);
7382 Qtime = intern_c_string ("time");
7383 staticpro (&Qtime);
7384 Qcutime = intern_c_string ("cutime");
7385 staticpro (&Qcutime);
7386 Qcstime = intern_c_string ("cstime");
7387 staticpro (&Qcstime);
7388 Qctime = intern_c_string ("ctime");
7389 staticpro (&Qctime);
7390 Qpri = intern_c_string ("pri");
7391 staticpro (&Qpri);
7392 Qnice = intern_c_string ("nice");
7393 staticpro (&Qnice);
7394 Qthcount = intern_c_string ("thcount");
7395 staticpro (&Qthcount);
7396 Qstart = intern_c_string ("start");
7397 staticpro (&Qstart);
7398 Qvsize = intern_c_string ("vsize");
7399 staticpro (&Qvsize);
7400 Qrss = intern_c_string ("rss");
7401 staticpro (&Qrss);
7402 Qetime = intern_c_string ("etime");
7403 staticpro (&Qetime);
7404 Qpcpu = intern_c_string ("pcpu");
7405 staticpro (&Qpcpu);
7406 Qpmem = intern_c_string ("pmem");
7407 staticpro (&Qpmem);
7408 Qargs = intern_c_string ("args");
7409 staticpro (&Qargs);
7411 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7412 doc: /* *Non-nil means delete processes immediately when they exit.
7413 A value of nil means don't delete them until `list-processes' is run. */);
7415 delete_exited_processes = 1;
7417 #ifdef subprocesses
7418 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7419 doc: /* Control type of device used to communicate with subprocesses.
7420 Values are nil to use a pipe, or t or `pty' to use a pty.
7421 The value has no effect if the system has no ptys or if all ptys are busy:
7422 then a pipe is used in any case.
7423 The value takes effect when `start-process' is called. */);
7424 Vprocess_connection_type = Qt;
7426 #ifdef ADAPTIVE_READ_BUFFERING
7427 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7428 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7429 On some systems, when Emacs reads the output from a subprocess, the output data
7430 is read in very small blocks, potentially resulting in very poor performance.
7431 This behavior can be remedied to some extent by setting this variable to a
7432 non-nil value, as it will automatically delay reading from such processes, to
7433 allow them to produce more output before Emacs tries to read it.
7434 If the value is t, the delay is reset after each write to the process; any other
7435 non-nil value means that the delay is not reset on write.
7436 The variable takes effect when `start-process' is called. */);
7437 Vprocess_adaptive_read_buffering = Qt;
7438 #endif
7440 defsubr (&Sprocessp);
7441 defsubr (&Sget_process);
7442 defsubr (&Sdelete_process);
7443 defsubr (&Sprocess_status);
7444 defsubr (&Sprocess_exit_status);
7445 defsubr (&Sprocess_id);
7446 defsubr (&Sprocess_name);
7447 defsubr (&Sprocess_tty_name);
7448 defsubr (&Sprocess_command);
7449 defsubr (&Sset_process_buffer);
7450 defsubr (&Sprocess_buffer);
7451 defsubr (&Sprocess_mark);
7452 defsubr (&Sset_process_filter);
7453 defsubr (&Sprocess_filter);
7454 defsubr (&Sset_process_sentinel);
7455 defsubr (&Sprocess_sentinel);
7456 defsubr (&Sset_process_window_size);
7457 defsubr (&Sset_process_inherit_coding_system_flag);
7458 defsubr (&Sset_process_query_on_exit_flag);
7459 defsubr (&Sprocess_query_on_exit_flag);
7460 defsubr (&Sprocess_contact);
7461 defsubr (&Sprocess_plist);
7462 defsubr (&Sset_process_plist);
7463 defsubr (&Sprocess_list);
7464 defsubr (&Sstart_process);
7465 defsubr (&Sserial_process_configure);
7466 defsubr (&Smake_serial_process);
7467 defsubr (&Sset_network_process_option);
7468 defsubr (&Smake_network_process);
7469 defsubr (&Sformat_network_address);
7470 #if defined(HAVE_NET_IF_H)
7471 #ifdef SIOCGIFCONF
7472 defsubr (&Snetwork_interface_list);
7473 #endif
7474 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
7475 defsubr (&Snetwork_interface_info);
7476 #endif
7477 #endif /* defined(HAVE_NET_IF_H) */
7478 #ifdef DATAGRAM_SOCKETS
7479 defsubr (&Sprocess_datagram_address);
7480 defsubr (&Sset_process_datagram_address);
7481 #endif
7482 defsubr (&Saccept_process_output);
7483 defsubr (&Sprocess_send_region);
7484 defsubr (&Sprocess_send_string);
7485 defsubr (&Sinterrupt_process);
7486 defsubr (&Skill_process);
7487 defsubr (&Squit_process);
7488 defsubr (&Sstop_process);
7489 defsubr (&Scontinue_process);
7490 defsubr (&Sprocess_running_child_p);
7491 defsubr (&Sprocess_send_eof);
7492 defsubr (&Ssignal_process);
7493 defsubr (&Swaiting_for_user_input_p);
7494 defsubr (&Sprocess_type);
7495 defsubr (&Sset_process_coding_system);
7496 defsubr (&Sprocess_coding_system);
7497 defsubr (&Sset_process_filter_multibyte);
7498 defsubr (&Sprocess_filter_multibyte_p);
7500 #endif /* subprocesses */
7502 defsubr (&Sget_buffer_process);
7503 defsubr (&Sprocess_inherit_coding_system_flag);
7504 defsubr (&Slist_system_processes);
7505 defsubr (&Sprocess_attributes);