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