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